1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
| #include <stdio.h> #include <stdlib.h> // 声明exit函数
typedef struct Node { int data; struct Node * pNext; }NODE,*PNODE;
PNODE createLinkList(void); void traverseLinkList(PNODE pHead);
void main() { PNODE pHead = NULL; pHead = createLinkList(); traverseLinkList(pHead); }
PNODE createLinkList(void) { int length; int i; int value;
PNODE phead = (PNODE)malloc(sizeof(NODE)); if(NULL == phead) { printf("内存分配失败,程序退出!\n"); exit(-1); }
PNODE pend = phead; pend->pNext = NULL;
printf("请输入链表的长度,len ="); scanf("%d",&length);
for(i= 0;i< length;i++){ printf("请输入第%d个节点的值 :",i); scanf("%d",&value); PNODE pNew =(PNODE)malloc(sizeof(NODE)); if(NULL == pNew) { printf("内存分配失败,程序退出!\n"); exit(-1); } pNew->data = value; pend->pNext = pNew; pNew->pNext = NULL; pend = pNew; }
return phead; }
void traverseLinkList(PNODE pHead) { PNODE p = pHead->pNext; while(NULL != p) { printf("%d ", p->data); p = p->pNext; } printf("\n"); }
|