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 }

 

posted on 2018-03-06 10:30  shunxiang  阅读(208)  评论(0编辑  收藏  举报