这个过程比较简单,就写了一个main函数
链表反转
#include <iostream>
using namespace std;
struct Node
{
int data;
Node* next;
};
int main()
{
Node *phead = NULL;
//构建链表
Node *ptail = NULL;
for(int i = 0;i < 10;i++)
{
Node *p = new Node;
p->data = i;
if(phead == NULL)
{
phead = p;
ptail = p;
ptail->next = NULL;
}
else
{
ptail->next = p;
ptail = ptail->next;
ptail->next = NULL;
}
}
//输出信息
Node *p = phead;
while(p !=NULL)
{
cout<<p->data<<" ";
p = p->next;
}
cout<<endl;
//反转链表
Node *phead_2 = NULL;
while(phead != NULL)
{
if(phead_2 == NULL)
{//如果是头结点
phead_2 = phead;
phead = phead->next;
phead_2->next = NULL;
}
else
{
p = phead;
phead = phead->next;
p->next = phead_2;
phead_2 = p;
}
}
//输出反转结果
p = phead_2;
while(p !=NULL)
{
cout<<p->data<<" ";
p = p->next;
}
cout<<endl;
system("pause");
return 1;
}
本文详细介绍了链表反转算法的实现过程,包括构建链表、输出信息和反转链表的操作。通过实例演示了如何使用C++语言进行链表操作。
298

被折叠的 条评论
为什么被折叠?



