数据结构实验之链表二:逆序建立链表
Time Limit: 1000ms Memory limit: 65536K 有疑问?点这里^_^
题目描述
输入
第二行依次输入N个整数,逆序建立单链表。
输出
示例输入
10 11 3 5 27 9 12 43 16 84 22
示例输出
22 84 16 43 12 9 27 5 3 11
提示
来源
示例程序
/*逆序建链表,是先建立头结点,然后插入第一个结点表示最后一个结点,后面插入的结点都往最后一个结点前面插入*/
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node *next;
};
int main()
{
struct node *head,*p,*q;
int i,n;
scanf("%d",&n);
head=(struct node *)malloc(sizeof(struct node));
head->next=NULL;
while(n--)
{
p=(struct node *)malloc(sizeof(struct node));
scanf("%d",&p->data);
p->next=head->next; /*此处两者的顺序不能颠倒,再插入结点的时候,先改变被删结点的后继,即,先让屁股插进来*/
head->next=p;
}
while(p!=NULL)
{
if(p->next==NULL)
printf("%d\n",p->data);
else printf("%d ",p->data);
p=p->next;
}
}