关于双向指针的初始化,插入与删除过程:
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 int length = 0;
5 int d;
6 struct node{
7 struct node * next;
8 struct node * prev;
9 int data;
10 };
11
12 /*链表初始化*/
13 int InitList(struct node * head)
14 {
15 struct node *p;
16 struct node *q;
17 head->next = NULL;
18 head->prev = NULL;
19
20 p = head;
21 printf("输入数据:\n");
22 scanf("%d", &d);
23 while(d > 0)
24 {
25 q = (struct node *)malloc(sizeof(struct node));
26 q->next = NULL;
27 q->data = d;
28 q->prev = p;
29 p->next = q;
30 p = p->next;
31
32 length++;
33 scanf("%d", &d);
34 }
35 return d;
36 }
37
38 /*插入一个节点*/
39 void ListInsert(struct node * head, int i, int e)
40 {
41 struct node *p;
42 struct node *q;
43 int j = 1;
44 p = head;
45 if(i > 0 && i<=length+1)
46 {
47 while(j < i)
48 {
49 p = p->next;
50 j++;
51 }
52 q = (struct node *)malloc(sizeof(struct node));
53 q->data = e;
54 q->next = p->next;
55 if(p->next)
56 p->next->prev = q;
57 q->prev = p;
58 p->next = q;
59 }
60 else
61 printf("输入节点的位置不正确");
62 }
63
64 /*删除节点*/
65 int ListDel(struct node *head, int i)
66 {
67 struct node *p;
68 int j = 0;
69 int d;
70 p = head;
71 while(j < i)
72 {
73 p = p->next;
74 j++;
75 }
76 d = p->data;
77 p->prev->next = p->next;
78 if(p->next)
79 p->next->prev = p->prev;
80 free(p);
81
82 return d;
83 }
84
85 /*打印链表*/
86 void print(struct node * head)
87 {
88 struct node *p;
89 struct node *q;
90 if(head)
91 {
92 p = head->next;
93 printf("正向输出\n");
94 while(p)
95 {
96 printf("%5d", p->data);
97 q = p;
98 p = p->next;
99 }
100 printf("\n逆向输出\n");
101 while(q->prev)
102 {
103 printf("%5d", q->data);
104 q = q->prev;
105 }
106 printf("\n");
107
108 }
109 }
110
111
112 void main()
113 {
114 struct node *head;
115 int i = 3;
116 int data = 11;
117 int d1;
118 head = (struct node *)malloc(sizeof(struct node));
119
120 d1 = InitList(head);
121 printf("所创建的链表:\n");
122 print(head);
123
124 printf("在3的位置插入数据11\n");
125 ListInsert(head, i, data);
126 print(head);
127
128 printf("删除3位置节点的数据\n");
129 ListDel(head, i);
130 print(head);
131 }