单链表的删除操作的实现
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 typedef struct LinkNode //单链表节点结构的定义
5 {
6 int data;
7 struct LinkNode *next;
8 }LinkNode;
9
10 void InitLinkList(LinkNode * &L)
11 {
12 /*单链表的初始化*/
13 L = (LinkNode*)malloc(sizeof(LinkNode));
14 L->next = NULL;
15 }
16
17 void CreateLinkList(LinkNode *&L, int n,int *num)
18 {
19 /*采用尾插法创建单链表*/
20 LinkNode* r = L;
21 for (int i = 0; i < n; ++i)
22 {
23 LinkNode * p =(LinkNode*)malloc(sizeof(LinkNode));
24 p->data = num[i];
25 p->next = r->next;
26 r->next = p;
27 r = p;
28 }
29 }
30
31 void DisList(LinkNode *L)
32 {
33 /*单链表的输出*/
34 LinkNode *l = L->next;
35 while(l)
36 {
37 printf("%d ",l->data);
38 l = l->next;
39 }
40 }
41
42 void DelLinkList(LinkNode *&L, int p)
43 {
44 /*删除指定参数所代表的节点*/
45 LinkNode *a = L;
46 LinkNode *b;
47 for(int i=0;i<p-2;i++)
48 {
49 a = a->next;
50 }
51 b = a->next;
52 a->next = a->next->next;
53 free(b);
54 }
55
56 int main(int argc, char const *argv[])
57 {
58 /*int n = 5;
59 int num[]={1,2,3,4,5};*/
60 int n, p;
61 int *num;
62
63 scanf("%d",&n);
64 num =(int*)malloc(n*sizeof(int));
65
66 for (int i = 0; i < n; ++i)
67 {
68 scanf("%d",&num[i]);
69 }
70
71 scanf("%d",&p);
72
73 /*判断输入值是否合法*/
74 if(p > n || p < 2)
75 {
76 printf("error!");
77 return 0;
78 }
79
80 LinkNode *L;
81 InitLinkList(L);
82 CreateLinkList(L,n,num);
83 DelLinkList(L,p);
84 DisList(L);
85 return 0;
86 }