数据结构实验之链表三:链表的逆置
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
链表的原理还是很简单的,但是挺长的容易错
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data; // 数据域
struct node *next;// 指针域
}*head, *p, *q, *k;//定义
struct node *creat(int 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;
}
return head;
}
void display(struct node *head)
{
p = head -> next;
while(p)
{
if(p -> next) printf("%d ",p -> data);
else printf("%d\n",p -> data);
p = p -> next;
}
}
int main()
{
int n;
scanf("%d",&n);
head = creat(n);
printf("%d\n",n);
display(head);
q = head -> next;
while(q)
{
k = q;
p = q -> next;
while(p)
{
if(p -> data == q -> data)
{
p = p -> next;
k -> next = p;
n--;
}
else
{
p = p -> next;
k = k -> next;
}
}
q = q -> next;
}
printf("%d\n",n);
display(head);
return 0;
}