#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node * next;
};
//顺序建立链表
struct node *creatw()
{
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;
tail->next=p;
tail=p;
}
return head;
}
//将链表逆置
struct node * reverse(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;
if (q!=NULL) {
q=q->next;
}
}
return head;
}
//输出逆序完以后的链表
void show(struct node *head)
{
struct node *r ;
r=head->next;
while (r!=NULL) {
if (r->next!=NULL) {
printf("%d ",r->data);
}else
printf("%d\n",r->data);
r=r->next;
}
}
int main(int argc, const char * argv[]) {
struct node *head;
struct node *s;
head=creatw();
s=reverse(head);
show(s);
return 0;
}
数据结构实验之链表三:链表的逆置
最新推荐文章于 2020-10-05 17:21:00 发布