单链表的建立

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 
 4 typedef int ElemType ;
 5 
 6 typedef struct LNode {            //定义一个单链表,指针域和数据域 
 7     ElemType data;
 8     struct LNode *next;
 9 }LNode , *LinkList; 
10 
11 
12 LinkList CreatList1(LinkList &L) {                //采用头插法建立单链表 
13     LNode *s;
14     int x;
15     L = (LinkList)malloc(sizeof(LNode));
16     L->next = NULL;
17     cin >> x;
18     while (x != 9999) {
19         s = (LNode *)malloc(sizeof(LNode));
20         s->data = x;
21         s->next = L->next;
22         L->next = s;
23         cin >> x;
24     }
25     return L;
26 } 
27 
28 
29 LinkList CreatList2(LinkList &L) {                    //采用尾插法建立单链表 
30     int x;
31     L = (LinkList) malloc(sizeof(LNode));
32     LNode *s, *r = L;
33     cin >> x;
34     while (x != 9999) {
35         s = (LNode *)malloc(sizeof(LNode));
36         s->data = x;
37         r->next = s;
38         s = r;
39         cin >> x;
40     }
41     return L;
42 } 
43 
44 
45 int main() {
46     LNode *L;
47     CreatList1(L);
48     LNode *p = L->next;//头插法建立链表,倒序输出 
49     while (p)    {
50         int n = p->data;
51         cout << n;
52         p = p->next;
53     } 
54     
55     
56     return 0;
57 } 

 

posted @ 2017-03-17 14:00  Tovi  阅读(145)  评论(0)    收藏  举报