采用三个指针来实现
#include<iostream>
using namespace std;
typedef struct LNode
{
int data;
struct LNode* next;
} *LinkList, LNode;
int Init_List(LinkList& L) //初始化链表
{
L = new LNode;
L->next = NULL;
return 1;
}
int func(LinkList& L) //逆转的具体函数
{
LNode* p, * q = new LNode;
q= L;
p = q;
LNode* r = L->next;
q->next = NULL; //将头指针的next赋值为NULL
while (r != NULL)
{
q = r; //q 指针移动到首元结点
r = r->next; //r 指针移动到第二个节点
q->next = p; //将首元结点的next指针指向前一个节点(头结点)
p = q; //p 指针移动到首元结点
}
L = p;
return 1;
}
int main()
{
LinkList L;
if (Init_List(L))
{
cout << "初始化成功!" << endl;
}
LNode* q = L;
int a[5] = { 1,2,3,4,5 };
for (int i = 0; i < 5; i++)
{
LNode* p = new LNode;
p->data = a[i];
p->next = NULL;
q->next = p; //尾插发创建一个带有头结点的单链表
q = p;
}
if (func(L))
{
cout << "逆转成功!" << endl;
}
LNode* p = L;
while (p ->next!= NULL) //头结点上不存在数字,所以在逆转的时候循环的停止条件是P->next==NULL
{
cout << p->data << " ";
p = p->next;
}
cout<<endl;
system("pause");
return 1;
}
最后输出结果为:
采用递归函数来实现
#include<iostream>
using namespace std;
typedef struct LNode
{
int data;
struct LNode* next;
} *LinkList, LNode;
int Init_List(LinkList& L) //初始化链表
{
L = new LNode;
L->next = NULL;
return 1;
}
LNode* reverse(LinkList &L)//逆转的函数的递归写法
{
if(L==NULL)
return NULL;
if(L->next==NULL)
return L;
LNode* second = L->next;
LNode* rest = reverse(second);
second->next = L;
L->next = NULL;
return rest; // rest 为链表的最后一个节点
}
int main()
{
LinkList L;
if (Init_List(L))
{
cout << "初始化成功!" << endl;
}
LNode* q = L;
int a[5] = { 1,2,3,4,5 };
for (int i = 0; i < 5; i++)
{
LNode* p = new LNode;
p->data = a[i];
p->next = NULL;
q->next = p; //尾插发创建一个带有头结点的单链表
q = p;
}
L = reverse(L);// 递归方法的调用
cout << "链表逆转成功!" << endl;
LNode* p = L;
while (p ->next!= NULL) //头结点上不存在数字,所以在逆转的时候循环的停止条件是P->next==NULL
{
cout << p->data << " ";
p = p->next;
}
cout<<endl;
system("pause");
return 1;
}