/*
时间:2015年10月13日08:23:18
功能:建立链表并且输出链表中的内容
知识点:struct,指针,malloc函数和stdlib.h头文件
总结:
*/
# include <stdio.h>
# include <malloc.h>
# include <stdlib.h>
struct Node
{
int data;
struct Node * pNext;
};
struct Node * create_list();
void traverse_list(struct Node * pHead);
int main(void)
{
struct Node * pHead = NULL;//null不行 要大写的
pHead = create_list();
traverse_list(pHead);
return 0;
}
struct Node * create_list()
{
int len;
int val;
int i;
struct Node * pHead = (struct Node *)malloc(sizeof(struct Node *));//要判断是否内存分配成功 malloc函数位于头文件<malloc.h>中
if(NULL == pHead)
{
printf("内存配失败,程序终止");
exit(-1);//位于头文件<stdlib.h>中
}
struct Node * pTail = pHead;
printf("请输入你要创建的链表的长度,len=");
scanf("%d",&len);
for(i = 0;i < len;i++)
{
//pTail = pHead;//应该在循环中之外
struct Node * pNew = (struct Node *)malloc(sizeof(struct Node));
if(pNew == NULL)
{
printf("内存分配失败,程序终止");
exit(-1);
}
printf("请输入第%d个节点的值:",i+1);
scanf("%d",&val);
pNew->data = val;//先在新节点里存入数据
pTail->pNext = pNew;//使pNew与pTail建立关系
pNew->pNext = NULL;//要加上,否则会在运行过程中出错
pTail = pNew;
}
return pHead;//感觉不要pTail也行,但试过后不行,不知为何?
}
void traverse_list(struct Node * pHead)
{
struct Node * p = pHead->pNext;
while(p != NULL)
{
printf("%d ",p->data);
p = p->pNext;//很重要
}
printf("\n");
return;//最好加上,好习惯
}
时间:2015年10月13日08:23:18
功能:建立链表并且输出链表中的内容
知识点:struct,指针,malloc函数和stdlib.h头文件
总结:
*/
# include <stdio.h>
# include <malloc.h>
# include <stdlib.h>
struct Node
{
int data;
struct Node * pNext;
};
struct Node * create_list();
void traverse_list(struct Node * pHead);
int main(void)
{
struct Node * pHead = NULL;//null不行 要大写的
pHead = create_list();
traverse_list(pHead);
return 0;
}
struct Node * create_list()
{
int len;
int val;
int i;
struct Node * pHead = (struct Node *)malloc(sizeof(struct Node *));//要判断是否内存分配成功 malloc函数位于头文件<malloc.h>中
if(NULL == pHead)
{
printf("内存配失败,程序终止");
exit(-1);//位于头文件<stdlib.h>中
}
struct Node * pTail = pHead;
printf("请输入你要创建的链表的长度,len=");
scanf("%d",&len);
for(i = 0;i < len;i++)
{
//pTail = pHead;//应该在循环中之外
struct Node * pNew = (struct Node *)malloc(sizeof(struct Node));
if(pNew == NULL)
{
printf("内存分配失败,程序终止");
exit(-1);
}
printf("请输入第%d个节点的值:",i+1);
scanf("%d",&val);
pNew->data = val;//先在新节点里存入数据
pTail->pNext = pNew;//使pNew与pTail建立关系
pNew->pNext = NULL;//要加上,否则会在运行过程中出错
pTail = pNew;
}
return pHead;//感觉不要pTail也行,但试过后不行,不知为何?
}
void traverse_list(struct Node * pHead)
{
struct Node * p = pHead->pNext;
while(p != NULL)
{
printf("%d ",p->data);
p = p->pNext;//很重要
}
printf("\n");
return;//最好加上,好习惯
}