数据结构实验之链表三:链表的逆置
Description
输入多个整数,以-1作为结束标志,顺序建立一个带头结点的单链表,之后对该单链表的数据进行逆置,并输出逆置后的单链表数据。
Input
输入多个整数,以-1作为结束标志。
Output
输出逆置后的单链表数据。
Sample
Input
12 56 4 6 55 15 33 62 -1
Output
62 33 15 55 6 4 56 12
Hint
不得使用数组。
第一种:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
int main()
{
struct node *head,*p,*q;
int x;
head=(struct node *)malloc(sizeof(struct node));
head->next=NULL;
while(~scanf("%d",&x))//输入
{
if(x==-1)
break;
else
{
p=(struct node *)malloc(sizeof(struct node));//
p->data=x;//赋值
p->next=head->next;//p所指向的结点插入头结点之后
head->next=p;
}
}
q=head->next;
while(q)//输出
{
if(q->next==NULL)
printf("%d\n",q->data);
else
printf("%d ",q->data);
q=q->next;
}
return 0;
}
第二:
#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;
}