链表的创建,添加结点,打印...

链表在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   

 

转载于:https://www.cnblogs.com/sjlove/archive/2013/05/08/3068069.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值