cocobear9  
一枚普通的zisuer(lll¬ω¬),努力每天多学一点点

输入:1 2 3 4 5 -1

输出:5 4 3 2 1 

此题考查头链表的创建之一 :头插法。所谓头插法是从一个空链表开始,重复读入数据,生成新结点,将读入的数据存放新结点的数据域中,然后讲新结点插入到当前链表的头结点之后,直至读入结束标志为止。

 

#include <stdio.h>
#include <stdlib.h>

 

typedef struct Node
{
int data ;
struct Node * pNext ;
}* PNODE ,NODE ;
PNODE creat_list(void) ;
void show_list(PNODE phead) ;

int main()
{
PNODE phead = NULL ;
phead = creat_list() ;
show_list(phead) ;
return 0 ;
}
PNODE creat_list(void)
{
int val;
PNODE phead = (PNODE)malloc(sizeof(NODE)) ; //为头指针开辟内存空间
phead->pNext = NULL ; //初始化空链表
// PNODE pNew =NULL ;//初始化新结点
while(1)
{
scanf("%d",&val);
if(val<0 ) break ;
PNODE pNew =(PNODE)malloc(sizeof(NODE)) ; //// 为新结点开辟内存空间
pNew->data = val ;
pNew->pNext = phead->pNext ;//! 将头指针所指向的下一个结点的地址,赋给新创建结点的next
phead->pNext = pNew ; //!把新结点挂到头结点后面(插入)

}

return phead ;
}
void show_list(PNODE phead)
{
PNODE p = phead->pNext ;
while(p!=NULL)
{
printf("%d ",p->data);
p=p->pNext ;
}
printf("\n");
}

 

posted on 2020-01-29 21:44  cocobear9  阅读(579)  评论(0编辑  收藏  举报