算法思想:把鏈表從表頭拆開,用頭插法從開始節點往表頭插入,就完成了逆置
代碼:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
typedef struct LNode{
int data;
struct LNode *next;
}LNode;
void create(LNode *&A,int n) //創建鏈表
{
int i,a[30];
LNode *s,*r;
A=(LNode *)malloc(sizeof(LNode));
A->next=NULL;
r=A;
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
s=(LNode *)malloc(sizeof(LNode));
s->data=a[i];
r->next=s;
r=r->next;
}
r->next=NULL;
}
void print(LNode *A) //輸出鏈表
{
LNode *p;
p=A;
while(p->next!=NULL)
{
printf("%d ",p->next->data);
p=p->next;
}
printf("\n");
}
void reverse(LNode *&A)
{
LNode *p,*q,*r;
p=A->next;
r=A;
r->next=NULL;
while(p!=NULL)
{
q=p->next;
p->next=r->next;
r->next=p;
p=q;
}
}
int main()
{
LNode *A;
int n;
scanf("%d",&n);
create(A,n);
reverse(A);
print(A);
return 0;
}