逆置单链表
1、基本声明
#include<stdio.h>
#include<stdlib.h>
typedef int datatype;
typedef struct node
{
datatype data;
struct node *next;
}LNode;
2、尾接法创建单链表
LNode* tail_create(LNode *head)
{
LNode *tail,*p;
datatype x;
head=(LNode *)malloc(sizeof(LNode));
head->next=NULL;
tail=head;
printf("please input data and end with -1:\n");//以-1终止输入
scanf("%d",&x);
while(x!=-1)
{
p=(LNode*)malloc(sizeof(LNode));
p->data=x;
p->next=NULL;
tail->next=p;
tail=p;
scanf("%d",&x);
}
return head;
}
3、逆置函数
void reverse(LNode* head)
{
LNode *p,*q;
p=head->next;//p先记下首元结点
head->next=NULL;//将头结点与后面的链表断开
while(p)
{
q=p;//用指针p将原来单链表的结点转运到新的单链表中
p=p->next;
q->next=head->next;//头插法
head->next=q;
}
}
4、测试函数
void show(LNode *head)
{
LNode *p=head->next;
while(p)
{
printf("%d ",p->data);
p=p->next;
}
}
int main()
{
LNode *p,*head;
head=tail_create(p);
reverse(head);
show(head);
return 0;
}
5、运行结果