单链表反转(非递归)
2013-02-26 21:40
197 查看
单链表的反转有很多种方法,这里最主要讲一下非递归方法中的移动指针的方法。
对于这种方法可能在移动指针的时候很容易出错,所以我想了一种的特殊的思考方法。
在创建链表的时候,有头插法和尾插法两种方法,而头插法创建的链表其数据的顺序刚好与输入的顺序相反,因此可以利用这个特点反转单链表。我们可以从新“创建”单链表,数据来源于原链表。
代码(C++):
对于这种方法可能在移动指针的时候很容易出错,所以我想了一种的特殊的思考方法。
在创建链表的时候,有头插法和尾插法两种方法,而头插法创建的链表其数据的顺序刚好与输入的顺序相反,因此可以利用这个特点反转单链表。我们可以从新“创建”单链表,数据来源于原链表。
代码(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; }
相关文章推荐
- 续:一个带头结点的单链表反转(递归)
- 【链表】非递归过程以O(N)反转单链表
- 经典算法——单链表反转的递归方法和非递归方法
- 递归,迭代,堆栈三种方式实现单链表反转(C++)
- 链表反转——迭代模型与递归模型
- 剑指Offer系列---(18)反转链表(递归与非递归实现)
- 遍历和递归实现双向链表反转
- 【剑指offer】递归循环两种方式反转链表
- 使用递归和非递归方式反转单向链表
- 使用非递归过程以O(N)时间反转单链表 使用常数附加空间
- 递归方法反转单向链表(C/C++)
- 链表反转C实现(递归与循环)
- 递归的方式反转链表
- 使用递归和非递归方式反转单向链表
- 递归方法反转链表
- 16、反转链表(递归方法)
- 单链表递归反转和非递归翻转
- 递归和非递归实现链表反转
- 【剑指offer】反转链表(递归+非递归)
- 边看边写(链表反转(递归和非递归))