问题描述
- C++简单链表创建出了问题,求大神解答
- #include
#include
using namespace std;
typedef struct NODE
{
int number;
string name;
string sex;
int age;
struct NODE *pNext;
}*PNODEnode;void travel_List(PNODE pHead)
{PNODE p=pHead->pNext; while(NULL!=p) { cout<<p->number<<"" ""; cout<<p->name<<"" ""; cout<<p->sex<<"" ""; cout<<p->age<<"" ""; p=p->pNext; } cout<<endl;
}
PNODE create_list(void)
{
PNODE pHead=new node;PNODE pTail=pHead;pTail->pNext=NULL;for(int i=0; i<=1; i++){ int num; string nm; string sx; int ag; cin>>num; getline(cinnm); getline(cinsx); cin>>ag; PNODE pNEW=new node; pNEW->number=num; pNEW->name=nm; pNEW->sex=sx; pNEW->age=ag; pTail->pNext=pNEW; pNEW->pNext=NULL; pTail=pNEW;}return pHead;
}
int main()
{PNODE pHead=NULL;pHead=create_list();travel_List(pHead);
}
解决方案
using namespace std;typedef struct NODE{ int number; string name; string sex; int age; struct NODE *pNext;}*PNODEnode;void travel_List(PNODE pHead){ PNODE p=pHead->pNext; while(NULL!=p) { cout<<p->number<<"" ""; cout<<p->name<<"" ""; cout<<p->sex<<"" ""; cout<<p->age<<"" ""; p=p->pNext; } cout<<endl;}PNODE create_list(void){ PNODE pHead=new node; PNODE pTail=pHead; pTail->pNext=NULL; for(int i=0; i<=1; i++) { int num; string nm; string sx; int ag; cout<<""num:""; cin>>num; cin.get(); cout<<""Name:""; getline(cinnm); cout<<""Sex:""; getline(cinsx); cout<<""Age:""; cin>>ag; PNODE pNEW=new node; pNEW->number=num; pNEW->name=nm; pNEW->sex=sx; pNEW->age=ag; pTail->pNext=pNEW; pNEW->pNext=NULL; pTail=pNEW; } return pHead;}int main(){ PNODE pHead=NULL; pHead=create_list(); travel_List(pHead);}
你试试这段代码。
解决方案二:
cin>>num;后面加一个cin.get()。清空键盘缓冲区。
时间: 2025-01-19 14:04:01