mydjm

 

链表插入操作~

 1 #include <iostream>
 2 using namespace std;
 3 
 4 
 5 typedef struct node
 6 {
 7     int data;
 8     struct node* next;
 9 }Node;//节点结构体
10 
11 
12 Node* create(int n)//初始化头指针为空~
13 {
14     Node* head=(Node*)(malloc(sizeof(Node)));
15     head->next=NULL;
16     head->data=n;
17     return head;
18 }
19 
20 void insert(Node* head,int x)//插入链表~
21 {
22     Node* h=head;
23     Node* p=(Node*)(malloc(sizeof(Node)));
24     p->next=NULL;
25     p->data=x;
26     while(h->next!=NULL)
27         h=h->next;
28     h->next=p;
29 }
30 
31 void print(Node* head)//打印链表~
32 {
33     Node* h=head;
34     while (h->next!=NULL)
35     {
36         cout<<h->data<<endl;
37         h=h->next;
38     }
39     cout<<h->data<<endl;
40 }
41 
42 
43 void main()
44 {
45     int i,n,x;
46     cout<<"input a number:\n";
47     cin>>n;
48     Node* head=create(n);
49     for (i=0;i<n;i++)
50     {
51         cin>>x;
52         insert(head,x);
53     }
54     cout<<"链表打印如下:"<<endl;
55     print(head);
56 
57 }

很基础滴东西~也很重要滴~

posted on 2012-05-10 10:33  mydjm  阅读(420)  评论(0编辑  收藏  举报

导航