11.25-学习笔记
单链表的逆置-大概思想就是新建立一个头结点,然后让之前的结点使用头插法插入到新建立的链表中。(这个也是使用快慢指针判断回文串中前半部分逆置的思想(我感觉是这样的))
//实现单链表的逆置
//逆置单链表就是新创建一个链表,然后让原始列表的每一个结点使用头插法插入到新链表中。
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
int data;
struct node * next;
}Lnode,*Linklist;
//使用尾插法创建单链表
Linklist creat()
{
Linklist L;
Lnode *s;
Lnode *q;
int e;
L=(Linklist)malloc(sizeof(Lnode));
L->next=NULL;
q=L;
while(1)
{
printf("请输入想要建立的链表元素(9999结束)\n");
scanf("%d",&e);
if(e!=9999)
{
s=(Linklist)malloc(sizeof(Lnode));
s->next=q->next;
q->next=s;
s->data=e;
q=s;
}
else
break;
}
q->next=NULL;
return L;
}
void pri(Linklist L)
{
L=L->next;
printf("当前的元素为:");
while(L!=NULL)
{
printf("%d",L->data);
L=L->next;
}
}
int length(Linklist L)
{
int num=0;
L=L->next;
while(L!=NULL)
{
num++;
L=L->next;
}
return num;
}
Linklist resever(Linklist L)
{
Lnode *s;
Linklist q;
int count;
count=length(L);
printf("count=%d",count);
q=(Linklist)malloc(sizeof(Lnode));
q->next=NULL;
L=L->next; //从第一个结点开始
// for(int i=0;i<count;i++)
//在这里开始我的编译器存在问题,一直循环不出来,我以为是我的循环条件没控制对,因此我就换了一种循环书写,结果还是出不来。然后我重启了电脑就行了。
/// {
// s=(Linklist)malloc(sizeof(Lnode));//申请一个s结点
// s->data=L->data;
// s->next=q->next;
// q->next=s;
// L=L->next;
// // printf("%d",length(q));
// }
while(L!=NULL)
{
s=(Linklist)malloc(sizeof(Lnode));//申请一个s结点
s->data=L->data;
s->next=q->next;
q->next=s;
L=L->next;
}
printf("ok\n");
return q;
}
int main()
{
Linklist L,q;
L=creat();
pri(L);
q=resever(L);
pri(q);
return 0;
}
大概思想就是我画的这样: