您的位置:首页 > 编程语言 > C语言/C++

单链表反转(非递归)

2013-02-26 21:40 197 查看
单链表的反转有很多种方法,这里最主要讲一下非递归方法中的移动指针的方法。

对于这种方法可能在移动指针的时候很容易出错,所以我想了一种的特殊的思考方法。

在创建链表的时候,有头插法和尾插法两种方法,而头插法创建的链表其数据的顺序刚好与输入的顺序相反,因此可以利用这个特点反转单链表。我们可以从新“创建”单链表,数据来源于原链表。

代码(C++):

#include<iostream>
using namespace std;

struct Node
{
int data;
Node* next;
};

bool init(Node**h)
{
*h=new Node();
if(!(*h))
return true;
return false;
}
//采用头插法从新“创建”链表
//节点采用链表head中的节点
void reverseList(Node*head)
{
Node *h,*temp;
h=head->next;
head->next=NULL;
while(h)
{
temp=h;//取下一个节点
h=h->next;

temp->next=head->next;//头插法
head->next=temp;
}
}

int main()
{
Node *head,*p;
init(&head);
cout<<"原列链表: ";
p=head;
for (int i=0;i<10;i++)
{
p->next=new Node();
p=p->next;
p->data=rand()%100;
p->next=NULL;
cout<<p->data<<"  ";
}
cout<<endl;
cout<<"反转后的链表: ";
reverseList(head);
p=head->next;
while(p)
{
cout<<p->data<<"  ";
p=p->next;
}
cout<<endl;
return 0;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 C++ 单链表