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 }