|
|
10鱼币
本帖最后由 Yogurt_lei 于 2012-4-3 10:38 编辑
求详解本链表程序 看不懂
# include <stdio.h>
# include <malloc.h>
# include <stdlib.h>
struct Node
{
int data; //数据域
struct Node * pNext; //指针域
};
struct Node * CreatList(void);
void TraverseList(struct Node *);
int main(void)
{
struct Node *pHead = NULL;
pHead = CreatList(); //创建非循环单链表
TraverseList(pHead);
return 0;
}
struct Node * CreatList(void)
{
int len, i, val;
//分配存放一个不存放有效数据的头结点
struct Node * pHead = (struct Node *)malloc(sizeof(struct Node));
if (NULL==pHead)
{
printf("分配失败,终止程序!\n");
exit(-1);
}
struct Node *pTail = pHead;
pTail->pNext = NULL;
printf("请输入你需要生成的链表的个数:len =");
scanf("%d", &len);
for ( i=0;i < len;++i )
{
printf("请输入第%d个节点的值:",i+1);
scanf("%d", &val);
struct Node * pNew = (struct Node *)malloc(sizeof(struct Node));
if (NULL == pNew)
{
printf("分配失败,终止程序!\n");
exit(-1);
}
pNew->data = val;
pTail->pNext = pNew;
pNew->pNext = NULL;
pTail = pNew;
}
return pHead;
}
bool EmptyList(struct Node *pHead)
{
if ( pHead->pNext == NULL ) //pHead->pNext == (*pHead).pNext
return true;
else
return false;
}
void TraverseList(struct Node *pHead)
{
struct Node *p = pHead->pNext;
while (NULL != p)
{
printf("%d\n", p->data);
p = p->pNext;
}
return;
}
主要是这一段逻辑不清楚
pNew->data = val;
pTail->pNext = pNew;
pNew->pNext = NULL;
pTail = pNew;
|
最佳答案
查看完整内容
pNew->data = val;
把刚才输入val的节点值赋给新的节点pNew的数据域
pTail->pNext = pNew;
把pNew这个结点插入到pTail这个节结点后面
pNew->pNext = NULL;
因为pNew后面没有结点了就把它的指针域用null赋值
pTail = pNew;
把pTail这个结点向后移一位变成pnew,让后面的赋值操作在一个循环里
有什么不懂得 ...
|