C语言实现链表的创建与遍历

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

打印结果:

 

posted @ 2023-02-06 18:09  Tony.Jia  阅读(146)  评论(0编辑  收藏  举报