# 数据结构 | 双向链表简单实现及图示

————————————————————————————————————————————

– – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – –

– – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – –

```  1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 typedef struct Node pNode;
5 struct Node
6 {
7     int data;
8     pNode *prev, *next;
9 };
10 /* 初始化链表，尾插法 */
11 pNode *InitList(pNode **head, int n)
12 {
13     pNode *p, *s;
16         exit(0);
20     int i;
21     for (i = 0; i < n; ++i)
22     {
23         s = (pNode *)malloc(sizeof(pNode));
24         if (s == NULL)
25             exit(0);
26         printf("Input the value of the %dth node:", i + 1);
27         scanf("%d", &s->data);
28         s->next = NULL;
29         p->next = s;
30         s->prev = p;
31         p = s;//p指向尾节点
32     }
33     return p;
34 }
35 /* 遍历打印 */
37 {
38     pNode *p;
41         printf("the list is empty\n");
42     while(p != NULL)
43     {
44         printf("%d ", p->data);
45         p = p->next;
46     }
47     printf("\n");
48 }
49 /* 清空链表 */
51 {
52     pNode *p;
54     {
56         p->next->prev = NULL;
58         free(p);
59     }
60 }
61 /* 查找链表内的某个值 */
63 {
64     int number;
65     printf("Values are about to be deleted:");
66     scanf("%d", &number);
67     pNode *p;
69     while(p != NULL)
70     {
71         if (p->data == number)
72         {
73             return number;
74         }
75         p = p->next;
76     }
77     return 0;
78 }
79 /* 删除链表中某个元素，令p的前驱节点和后驱节点相互指向即可，如果p是尾节点则直接将前驱节点指向NULL*/
80 void DelNumqList(pNode **head, int n)
81 {
82     int i;
83     pNode *p;
85     for (i = 1; i < n; ++i)
86         p = p->next;
87     if(p->next == NULL)
88     {
89         p->prev->next = NULL;
90         free(p);
91     }
92     else
93     {
94         p->next->prev = p->prev;
95         p->prev->next = p->next;
96         free(p);
97     }
98 }
99 int main(int argc, char const *argv[])
100 {
101     int n, element, flag;
103     /***************************************************************/
104     printf("Please input the size of the list:");
105     scanf("%d", &n);
107     printf("%d %d \n", head->next->data, last->data); //打印为第一个元素和最后一个元素
109     /***************************************************************/
111     if (flag > 0 && flag <= n)
112     {
115     }
116     else
117         printf("Element does not exist, cannot be deleted\n");
118     /***************************************************************/