单向链表创建和输出的问题
下面这个程序是不是把首结点给漏掉了,是从pHead->pNext指向的那个结点开始的。感觉是这样,和书里的写法不一样,感觉就是漏了一个首结点的数据。求指导
程序代码:
// // main.c // 链表创建和链表遍历算法演示复习 // // Created by Hu Keming on 13-5-27. // Copyright (c) 2013年 Hu Keming. All rights reserved. // # include "stdio.h" # include "stdlib.h" typedef struct Node { int data; struct Node *pNext; }NODE, *PNODE; PNODE create_list(void); void traverse_list(PNODE pHead); int main(void) { PNODE pHead = NULL; // 等价于 struct Node * pHead = NULL; //create_list()函数功能:创建一个非循环单链表,并将该链表的头结点的地址赋给pHead pHead = create_list(); traverse_list(pHead); return 0; } PNODE create_list(void) { int len; int i; int val; //分配了一个不存放有效数据的头节点 PNODE pHead = (PNODE)malloc(sizeof(NODE)); if (NULL == pHead) { printf("分配失败,程序终止!\n"); exit (-1); } PNODE pTail = pHead; pTail->pNext = NULL; printf("请输入您需要生成的结点的个数: len = "); scanf("%d", &len); for (i=0; i<len; i++) { printf("请输入第%d个节点的值: ", i+1); scanf("%d", &val); PNODE pNew = (PNODE)malloc(sizeof(NODE)); if (NULL == pNew) { printf("分配失败,程序终止!\n"); exit (-1); } pNew->data = val; pTail->pNext = pNew; pNew->pNext = NULL; pTail =pNew; } return pHead; } void traverse_list(PNODE pHead) { PNODE p = pHead->pNext; while (NULL != p) { printf("%d ", p->data); p = p->pNext; } printf("\n"); return; }