1 #include <stdio.h>
2 #include <stdlib.h>
3 typedef int ElemType;
4 typedef struct LNode{
5 ElemType data;
6 struct LNode *next;
7 }LNode,*LinkList;
8 //头插法新建链表
9 LinkList CreatList1(LinkList &L)
10 {
11 LNode *s;int x;
12 //带头节点的链表
13 L=(LinkList)malloc(sizeof(LNode));
14 L->next=NULL;
15 scanf("%d",&x);
16 while(x!=9999){
17 s=(LNode*)malloc(sizeof(LNode));
18 s->data=x;
19 s->next=L->next;
20 L->next=s;
21 scanf("%d",&x);
22 }
23 return L;
24 }
25 //尾插法新建链表
26 LinkList CreatList2(LinkList &L)
27 {
28 int x;
29 L=(LinkList)malloc(sizeof(LNode));//带头节点的链表
30 LNode *s,*r=L;
31 scanf("%d",&x);
32 while(x!=9999){
33 s=(LNode*)malloc(sizeof(LNode));
34 s->data=x;
35 r->next=s;
36 r=s;//r指向新的表尾结点
37 scanf("%d",&x);
38 }
39 r->next=NULL;
40 return L;
41 }
42 //按序号查找结点值
43 LNode *GetElem(LinkList L,int i)
44 {
45 int j=1;
46 LNode *p=L->next;
47 if(i==0) return L;
48 if(i<1) return NULL;
49 while(p&&j<i){
50 p=p->next;
51 j++;
52 }
53 return p;
54 }
55 //按值查找
56 LNode *LocateElem(LinkList L,ElemType e)
57 {
58 LNode *p=L->next;
59 while(p!=NULL&&p->data!=e){
60 p=p->next;
61 }
62 return p;
63 }
64 //新结点插入第i个位置
65 bool ListFrontInsert(LinkList L,int i,ElemType e)
66 {
67 LinkList p=GetElem(L,i-1);
68 if(NULL==p) return false;
69 //为新插入的结点申请空间
70 LinkList s=(LNode*)malloc(sizeof(LNode));
71 s->data=e;
72 s->next=p->next;
73 p->next=s;
74 return true;
75 }
76 //删除第i个结点
77 bool ListDelete(LinkList L,int i)
78 {
79 LinkList p=GetElem(L,i-1);
80 if(p==NULL) return false;
81 LinkList q;
82 q=p->next;
83 p->next=q->next;
84 free(q);
85 return true;
86 }
87 //打印链表中每个结点的值
88 void PrintList(LinkList L)
89 {
90 L=L->next;
91 while(L!=NULL){
92 printf("%3d",L->data);
93 L=L->next;
94 }
95 printf("\n");
96 }
97 int main()
98 {
99 LinkList L;
100 LinkList search;
101 //头插法新建链表,输入数据可以为3 4 5 6 7 9999
102 //CreatList1(L);
103 //尾插法新建链表,输入数据可以为3 4 5 6 7 9999
104 CreatList2(L);
105 PrintList(L);
106 search=GetElem(L,2);
107 if(search!=NULL){
108 printf("按序号查找成功\n");
109 printf("%3d\n",search->data);
110 }
111 search=LocateElem(L,6);
112 if(search!=NULL){
113 printf("按值查找成功\n");
114 printf("%3d\n",search->data);
115 }
116 ListFrontInsert(L,2,99);
117 PrintList(L);
118 ListDelete(L,4);
119 printf("删除第四个结点成功\n");
120 PrintList(L);
121 system("pause");
122 }