C语言非循环单链表实现插入和遍历

#include
#include

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;
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(pHead == NULL){
printf(“内存分配失败,程序终止\n”);
exit(-1);
}
PNODE pTail = pHead;
pTail->pNext = NULL;

printf(“请输入需要生成的链表的结点的个数len=”);
scanf("%d",&len);
for(i=0;i printf(“请输入第%d个结点的值”,i+1);
scanf("%d",&val);
PNODE pNew = (PNODE)malloc(sizeof(NODE));
if(pNew == NULL){
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(p != NULL){
printf("%d",p->data);
p = p->pNext;
}
printf("\n");
return;
}

你可能感兴趣的:(C数据结构)