用单链表作为存储结构写一实现就地逆置的算法

来源:百度知道 编辑:UC知道 时间:2024/06/14 08:16:35

完整的code如下:

#include "stdio.h"
#include"malloc.h"

typedef struct node
{
int data;
struct node *next;
}link;

link *creat(int n) //创建链表
{
link *head,*p,*s;
int i;
p=head=(link *)malloc(sizeof(link));
for(i=1;i<=n;i++)
{
s=(link *)malloc(sizeof(link));
scanf("%d",&s->data);
p->next=s;
p=s;
}
p->next=NULL;
return head;
}

void reverse(link *head)//原地置换
{
link *p,*s,*t;
p=head;
s=p->next;
while(s->next!=NULL)//主要置换过程
{
t=s->next;
s->next=p;
p=s;
s=t;
}
s->next=p;
head->next->next=NULL;//收尾
head->next=s;//赋头
}

void display(link *head)//显示链表内容
{
link *p;
p=head->next;
while(p!=NULL)
{
printf("%d ",p->data);
p=p-