标签:
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <malloc.h> 4 #include <stdbool.h> 5 6 typedef struct Node{ 7 int data; //数据域 8 struct Node * pNext; //指针域 9 }NODE, * PNODE; //NODE等价于struct Node, * PNODE等价于struct Node * 10 11 PNODE createList(); 12 void traverseList(PNODE pHead); 13 14 int main() 15 { 16 17 PNODE pHead = NULL; //等价于struct Node * pHead = NULL; 18 pHead = createList(); //createList()函数功能:创建一个非循环单链表 19 //并将该链表的头节点的地址赋给pHead 20 traverseList(pHead); // 21 22 system("pause"); 23 return 0; 24 } 25 26 PNODE createList(void){ 27 int len; //用来存放有效节点的个数 28 int i; 29 int val; //用来临时存放用户输入的节点的值 30 31 //分配了一个不存放有效数据的头节点 32 PNODE pHead = (PNODE)malloc(sizeof(NODE)); 33 if(NULL == pHead){ 34 printf("分配失败!\n"); 35 exit(-1); 36 } 37 38 //创建一个永远指向尾节点的指针 39 PNODE pTail = pHead; 40 pTail->pNext = NULL; 41 42 printf("请输入您需要生成的链表节点的个数:len = "); 43 scanf("%d", &len); 44 45 46 for(i = 0; i < len; ++i){ 47 printf("请输入第%d个节点的值:", i+1); 48 scanf("%d", &val); 49 50 PNODE pNew = (PNODE)malloc(sizeof(NODE)); 51 if(NULL == pNew){ 52 printf("分配失败!\n"); 53 exit(-1); 54 } 55 pNew->data = val; 56 pTail->pNext = pNew; 57 pNew->pNext = NULL; 58 pTail = pNew; 59 60 } 61 return pHead; 62 } 63 64 void traverseList(PNODE pHead){ 65 PNODE p = pHead->pNext; 66 67 while(p != NULL){ 68 printf("%d ", p->data); 69 p = p->pNext; 70 } 71 72 printf("\n"); 73 }
标签:
原文地址:http://www.cnblogs.com/aladdin-light/p/5550863.html