试编写算法将带头结点的单链表就地逆置,所谓"就地"是这辅助空间的复杂度为O(1)
#include<stdio.h>
#include<stdlib.h>
typedef struct LNode {
int data;
struct LNode *next;
} LNode, *LinkList;
LinkList List_TailInsert(LinkList &L) {
int x;
L=(LinkList)malloc(sizeof(LNode));
L->data=999999;
LNode *s, *r=L;
printf("请输入数值\n");
scanf("%d",&x);
while(x!=9999) {
s=(LNode *)malloc(sizeof(LNode));
s->data = x;
r->next = s;
r=s;
scanf("%d",&x);
}
r->next = NULL;
return L;
}
void print(LinkList L) {
printf("\n");
if(L->next==NULL)
printf("该链表为空");
LNode *p= L->next;
while(p!=NULL) {
printf("%d ",p->data);
p=p->next;
}
}
void inverse1(LinkList &L) {
LNode *p,*r;
p=L->next;
L->next=NULL;
while(p!=NULL) {
r=p->next;
p->next = L->next;
L->next = p;
p = r;
}
}
void inverse2(LinkList &L) {
LNode *pre,*p=L->next,*r=p->next;
p->next=NULL;
while(r!=NULL) {
pre = p;
p=r;
r=r->next;
p->next=pre;
}
L->next=p;
}
int main() {
LinkList L=NULL;
int x;
List_TailInsert(L);
print(L);
inverse2(L);
print(L);
return 0;
}
运行结果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/f7c6bc6a21ab184e314bba78fa1f0d0e.png)