数据结构实验之链表二:逆序建立链表
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
输入整数个数N,再输入N个整数,按照这些整数输入的相反顺序建立单链表,并依次遍历输出单链表的数据。
Input
第一行输入整数N;;
第二行依次输入N个整数,逆序建立单链表。
Output
依次输出单链表所存放的数据。
Sample Input
10
11 3 5 27 9 12 43 16 84 22
Sample Output
22 84 16 43 12 9 27 5 3 11
//建立逆序链表的精华就在于让新的结点指针域记住插入的前一个结点的指向,保存好前一个节点的指向后前一个结点就可以指向新的结点,前一个结点->新的结点->后一个结点,但要注意地址不能丢,所以插入的时候要先记好下一个的结点
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};//链表是把结点连接起来,首先建立链表的结点,里面存放数据域和指针域
struct node *creat(int n)
{
int i;
struct node *head,*p;
head=(struct node *)malloc(sizeof(struct node));
head->next=NULL;//申请一个头节点让它为空
for(i=1; i<=n; i++)
{
p=(struct node *)malloc(sizeof(struct node));
scanf("%d",&p->data);
p->next=head->next;//要逆序插入链表就要把顺序输入的p结点插在链表最后,我们假设已经有头结点和p,如果再插入一个新的结点,新的结点就要与p连接起来,如果要连接起来那就让新的结点指向p的地址,p的地址由head->next记着,新的p->next=head->next,保存下head的指针域再给他一个新的指针域同时让头结点和新的p连接在一起,就让head->next=新的p
head->next=p;//建立p之后
}
return head;
};
void print(struct node *head)
{
int n=0;
struct node *p;
p=head->next;
while(p)//只要p不为空
{
n++;
if(n==1)
printf("%d",p->data);
else
printf(" %d",p->data);//输出p所保存的数据,输出结束后指向下一个
p=p->next;
}
printf("\n");//n保证空格数量完全一致
}
int main()
{
int n;
scanf("%d",&n);
struct node *head;
head=creat(n);
print(head);
return 0;
}