链表在C/C++中是一种比较重要的数据结构,属于线性表.
写了较好理解的代码,方便进行理解和实际的操作,为了方便理解及简化参数,第一个程序将head及,current指针设为全局变量.
1 #include <iostream> 2 using namespace std; 3 4 struct Node 5 { 6 int info; 7 Node *next; 8 }; 9 10 Node *head=NULL; 11 Node *current=NULL; 12 13 void CreateList() 14 { 15 head=new Node(); 16 head->next=NULL; 17 current=head; 18 } 19 20 void AddNode(int ele) 21 { 22 Node *node=new Node(); 23 node->info=ele; 24 node->next=NULL; 25 current->next=node; 26 current=node; 27 } 28 29 void display() 30 { 31 current=head->next; 32 while(current!=NULL) 33 { 34 cout<<current->info<<" "; 35 current=current->next; 36 } 37 cout<<endl; 38 } 39 40 41 int main(void) 42 { 43 CreateList(); 44 int n,ele; 45 cout<<"input the node number to be created"<<endl; 46 cin>>n; 47 cout<<"input....."<<endl; 48 while(n--) 49 { 50 cin>>ele; 51 AddNode(ele); 52 } 53 cout<<"Printing...."<<endl; 54 display(); 55 getchar(); 56 return 0; 57 } 58 59
虽然上面的代码看起来比较简洁,但是不太规范,将head,current指针声明为全局变量对于一个系统来说是致命的,因此应将其声明为局部变量。
代码修改如下:
1 #include <iostream> 2 using namespace std; 3 4 struct Node 5 { 6 int info; 7 Node *next; 8 }; 9 10 Node* CreateList() 11 { 12 Node *head=new Node(); 13 head->next=NULL; 14 return head; 15 } 16 17 void AddNode(Node *head ,int ele) 18 { 19 /* 开辟新的节点 */ 20 Node *node=new Node(); 21 node->info=ele; 22 node->next=NULL; 23 Node *p=head; 24 while(p->next!=NULL) 25 { 26 p=p->next;//寻找尾部结点 27 } 28 p->next=node;//添加新的尾部结点 29 } 30 31 void display(Node *head) 32 { 33 Node *p=NULL; 34 p=head->next; 35 while(p!=NULL) 36 { 37 cout<<p->info<<" "; 38 p=p->next; 39 } 40 cout<<endl; 41 } 42 43 44 int main(void) 45 { 46 Node *head=CreateList(); 47 int n,ele; 48 cout<<"input the node number to be created"<<endl; 49 cin>>n; 50 cout<<"input....."<<endl; 51 while(n--) 52 { 53 cin>>ele; 54 AddNode(head,ele); 55 } 56 cout<<"Printing...."<<endl; 57 display(head); 58 getchar(); 59 return 0; 60 } 61 62