数据结构实验之链表三:链表的逆置
Problem Description
输入多个整数,以-1作为结束标志,顺序建立一个带头结点的单链表,之后对该单链表的数据进行逆置,并输出逆置后的单链表数据。
Input
输入多个整数,以-1作为结束标志。
Output
输出逆置后的单链表数据。
Sample Input
12 56 4 6 55 15 33 62 -1
Sample Output
62 33 15 55 6 4 56 12
扫描二维码关注公众号,回复:
2549500 查看本文章
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};//链表是把结点连接起来,首先建立链表的结点,里面存放数据域和指针域
struct node *creat()
{
int a;
struct node *head,*p,*tail;
head=(struct node *)malloc(sizeof(struct node));
head->next=NULL;
tail=head;//申请一个头节点让它为空,让尾指针指向
while(scanf("%d",&a)&&a!=-1)
{
p=(struct node *)malloc(sizeof(struct node));
p->data=a;
p->next=NULL;//p现在是一个存放了数据和指针的结点
tail->next=p;//要把p连接在链表中就要把p连接在尾结点之后,要连接尾结点和p,如果想要把尾结点和p连接在一起,那就要把p的地址记下来,用tail记p的地址,就是tail->next=p,这样就把p的地址记下来了,
tail=p; //连接起新的链表之后,就需要把尾结点放在最后,tail=p
}
return head;
};
void creat1(struct node *head)
{
struct node *p,*q;
p=head->next;
head->next=NULL;
q=p->next;//保存指向他的地址号
while(p!=NULL)
{
p->next=head->next;//是逆置,就是要把遍历的结点插到头结点后面,插入的时候先保存插入结点的指针域
head->next=p;
p=q;//p插入完毕,进行下一个结点的操作,p=q就能让指针指向后一个
if(q)
q=p->next;//如果q没到最后才往后指
}
};
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()
{
struct node *h1;
h1=creat();
creat1(h1);
print(h1);
return 0;
}
注释:这个题跟逆序建链表又有不同,逆序建链表是新的结点,只需要按照输入顺序插入,而逆置链表是已经排好的链表再去逆置,每个结点都已经连接起来了,而在逆置链表的时候主要的点在于保存地址号,插入的时候要从前面开始把结点断开,断开的时候断开前面的和后面的,采用两个指针的方式能在断开结点的时候保留住两个指针域