转自http://www.nowamagic.net/librarys/veda/detail/1803
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <memory.h>
typedef int ElemType; /* ElemType类型根据实际情况而定,这里假设为int */
/* 定义单链表结点类型 */
typedef struct Node{
ElemType element;
struct Node *next;
}Node;
/* 1.初始化线性表,即置单链表的表头指针为空 */
void initList(Node **pNode)
{
*pNode = NULL;
printf("initList函数执行,初始化成功\n");
}
/* 2.创建线性表,此函数输入负数终止读取数据*/
Node *creatList(Node *pHead)
{
Node *p1;
Node *p2;
p1=p2=(Node *)malloc(sizeof(Node)); //申请新节点
if(p1 == NULL || p2 ==NULL)
{
printf("内存分配失败\n");
exit(0);
}
memset(p1,0,sizeof(Node));
scanf("%d",&p1->element); //输入新节点
p1->next = NULL; //新节点的指针置为空
while(p1->element > 0) //输入的值大于0则继续,直到输入的值为负
{
if(pHead == NULL) //空表,接入表头
{
pHead = p1;
}
else
{
p2->next = p1; //非空表,接入表尾
}
p2 = p1;
p1=(Node *)malloc(sizeof(Node)); //再重申请一个节点
if(p1 == NULL || p2 ==NULL)
{
printf("内存分配失败\n");
exit(0);
}
memset(p1,0,sizeof(Node));
scanf("%d",&p1->element);
p1->next = NULL;
}
printf("creatList函数执行,链表创建成功\n");
return pHead; //返回链表的头指针
}
/* 3.打印链表,链表的遍历*/
void printList(Node *pHead)
{
if(NULL == pHead) //链表为空
{
printf("PrintList函数执行,链表为空\n");
}
else
{
while(NULL != pHead)
{
printf("%d ",pHead->element);
pHead = pHead->next;
}
printf("\n");
}
}
int main()
{
Node *pList = NULL;
int length = 0;
ElemType posElem;
initList(&pList); //链表初始化
printList(pList); //遍历链表,打印链表
printf("请为链表输入节点值,输入负数退出 \n");
pList=creatList(pList); //创建链表
printList(pList);
}