c语言双向链表

c语言双向链表的创建、遍历。

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <string.h>
 4 #include <math.h>
 5 
 6 typedef struct Node
 7 {
 8     int data;
 9     int index;
10     struct Node *prev, *next;
11 }NODE;
12 
13 //创建双向链表
14 NODE* CreateList(int length)
15 {
16     NODE *pTail = NULL;
17     NODE *pNew = NULL;
18     NODE *pHead = (NODE*)malloc(sizeof(NODE));  //创建头指针
19     if (pHead == NULL)
20     {
21         printf("create List failed\r\n");
22         return NULL;
23     }
24     pHead->data = random()%1000;
25     pHead->prev = NULL;
26     pHead->next = NULL;
27     pTail = pHead;
28     
29     int i;
30     for(i = 1; i < length; i++)
31     {
32         pNew = (NODE*)malloc(sizeof(NODE));
33         if (pNew == NULL)
34         {
35             printf("create List failed\r\n");
36             return NULL;
37         }
38         pNew->data = random()%1000;
39         pNew->prev = pTail; 
40         pNew->next = NULL;
41         
42         pTail->next = pNew;
43         pTail = pNew;
44     }
45     return pHead;
46 } 
47 
48 void printList(NODE* pHead)
49 {
50     int count = 0;
51     if (pHead == NULL)
52     {
53         return;
54     }
55     while(pHead)
56     {
57         printf("%2d: %d\r\n", count, pHead->data);
58         count++;
59         pHead = pHead->next;
60     }    
61 }
62 
63 int main(int argc, char** argv)
64 {
65     NODE *pHead = CreateList(10);
66     
67     printList(pHead);
68 }

 

转载于:https://www.cnblogs.com/shawn-meng/p/8512916.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值