单链表就地逆转
//单链表逆转
bool Reverse(LinkList &L){
LNode *p=NULL,*q=L->next,*h;
if(q==NULL){
return false;
}
while(q!=NULL){
h=q->next;
q->next=p;
p=q;
q=h;
}
L->next=p;
return true;
}
验证
#include <stdio.h>
#include <stdlib.h>
typedef int ElemType;
typedef struct LNode{
ElemType data;
struct LNode *next;
}LNode,*LinkList;
//带头结点
//单链表逆转
bool Reverse(LinkList &L){
LNode *p=NULL,*q=L->next,*h;
if(q==NULL){
return false;
}
while(q!=NULL){
h=q->next;
q->next=p;
p=q;
q=h;
}
L->next=p;
return true;
}
//单链表初始化,带头结点!!!!!!!
bool InitList(LinkList &L){//这里传地址是因为要改变它
L=(LNode*)malloc(sizeof(LNode));
L->next=NULL;
return true;
}
//求表长
int Length(LinkList L){//这里不用传是因为只需要求表长,而不需要改变原本的链表
if(L->next==NULL){
return 0;
}
int n=0;
LNode *p=L;
while(p->next!=NULL){
n+=1;
p=p->next;
}
return n;
}
//按序号查找节点
LNode *GetElem(LinkList L,int i){
LNode *p=L;
int j=0;
while(p!=NULL && j<i){
p=p->next;
j++;
}
return p;//返回一个指针
}
//按值查找表节点
LNode *LocateElem(LinkList L,ElemType e){
LNode *p=L->next;//不查头结点的data
while(p!=NULL && p->data!=e){
p=p->next;
}
return p;
}
//插入节点操作
//将值为e的节点插入单链表第i个位置
bool ListInsert(LinkList &L,int i,ElemType e){
LNode *p=L;
int j=0;
while(p!=NULL && j<i-1){//找到该位置的前一个
p=p->next;
j++;
}
if (j!=i-1 || p==NULL){//i值不合法
return false;
}
LNode *s=(LNode *)malloc(sizeof(LNode));
s->data=e;
s->next=p->next;
p->next=s;
return true;
}
//删除节点操作
//删除第i个节点
bool ListDelete(LinkList &L,int i,ElemType &e){//这个e让外界获取所删除的值
LNode *p=L;
int j=0;
while (p!=NULL && j<i-1){
p=p->next;
j++;
}
if(p==NULL || j!=i-1 ||p->next==NULL){//这里还得注意第i个位置本身不能没有
return false;
}
LNode *q=p->next;
e=q->data;
p->next=q->next;
free(q);
return true;
}
//采用头插法建立单链表
LinkList List_HeadInsert(LinkList &L){
LNode *s;
ElemType x;
scanf("%d",&x);
while(x!=1234){//输入1234结束
s=(LNode*)malloc(sizeof(LNode));
s->data=x;
s->next=L->next;
L->next=s;
scanf("%d",&x);
}
return L;
}
//采用尾插法建立单链表
LinkList List_TailInsert(LinkList &L){
LNode *s,*p=L;
ElemType x;
scanf("%d",&x);
while(x!=1234){
s=(LNode*)malloc(sizeof(LNode));
s->data=x;
p->next=s;
p=s;
scanf("%d",&x);
}
p->next=NULL;
return L;
}
//打印链表
bool PrintList(LinkList L){
if(L->next==NULL){
return false;
}
LNode *p=L->next;
while(p!=NULL){
printf("%d ",p->data);
p=p->next;
}
printf("\n");
return true;
}
//主函数
int main(){
LinkList L;
if(InitList(L)){
L=List_TailInsert(L);//尾差法
}
if(!PrintList(L)){
printf("输出失败!");
}
Reverse(L);//逆转单链表
if(!PrintList(L)){
printf("输出失败!");
}
return 0;
}