摘要:老师的要求是用函数实现对于链表的各部分操作,由于对函数的应用还不是那么熟练,所以先放在一个里面写了,写这篇博客来整理一下对于链表逆置的思路
链表逆置的步骤:
1、根本题目要求进行顺序或者逆序建表
2、将head与后面的链表拆开
3、q放在p的后面帮着保存p后面的链表,防止q插进去之后,后面的部分丢失
4、按照逆序插入的方法进行插入
5、输出
#include<stdio.h>
#include<stdlib.h>
struct node//常规建立结点
{
int data;
struct node *next;
};
int main()
{
struct node *head,*p,*q,*tail;//设置需要用到的指针
int k;
head=(struct node*)malloc(sizeof(struct node));
head->next=NULL;
tail=head;//指针建立前的准备工作
while(~scanf("%d",&k))
{
if(k==-1)
break;
p=(struct node*)malloc(sizeof(struct node));
p->data=k;
p->next=NULL;//顺序建表要在这里指向NULL
tail->next=p;
tail=p;
}
p=head->next;
head->next=NULL;
q=p->next;//逆序前的准备
while(p)
{
p->next=head->next;
head->next=p;//常规的逆序建立步骤
p=q;
if(q)
q=q->next;//p,q双双往后移动
}
p=head->next;//开始输出
while(p)
{
if(p->next)
printf("%d ",p->data);
else
printf("%d\n",p->data);
p=p->next;
}
return 0;
}