单链表反转递归与非递归算法
2012-08-08 20:14
274 查看
1. 代码如下:
View Code
2. 在非递归算法(迭代算法)中,需要注意的是边界条件检查问题,这里巧妙地只检查curr是否为空,初始情况下将pre设置为NULL,在curr不为空的情况下定义next指针,之后迭代逐次向后修改链表中的指针。
3. 在递归算法中,最后一句p=rest保证rest一直指向反转链表的头部,不会改变,还没理解这个究竟是怎样做到的。
参考文章:
http://www.leetcode.com/2010/04/reversing-linked-list-iteratively-and.html#comment-23502
View Code
#include <iostream> #include <cassert> using namespace std; struct Node { Node* m_next; int m_data; Node(int data=0,Node* next=NULL) { this->m_data=data; this->m_next=next; } }; Node* CreateList(int *elem, int length) { assert(elem && length>0); Node* p=new Node(*(elem+length-1),NULL); for (int i=length-2;i>=0;i--) { p=new Node(*(elem+i),p); } return p; } void DestroyList(Node* &p) { if (!p) { return ; } Node* tmp=p; while(p) { tmp=p; p=p->m_next; delete tmp; } } void print(Node* p) { if (!p) { return ; } while(p) { cout<<p->m_data<<" "; p=p->m_next; } cout<<endl; } void IterativeReverse(Node* &p) { if (!p) { return ; } Node* pre=NULL; Node* curr=p; while (curr) { Node* next=curr->m_next; curr->m_next=pre; pre=curr; curr=next; } p=pre; } void RecursiveReverse(Node* &p) { if (!p) { return ; } Node* rest=p->m_next; if (!rest) { return ; } RecursiveReverse(rest); p->m_next->m_next=p; p->m_next=NULL; p=rest; } int main() { enum {length=8}; int elem[length]={23,43,12,0,14,1,17,9}; Node* pList=CreateList(elem,length); print(pList); //IterativeReverse(pList); RecursiveReverse(pList); print(pList); DestroyList(pList); return 0; }
2. 在非递归算法(迭代算法)中,需要注意的是边界条件检查问题,这里巧妙地只检查curr是否为空,初始情况下将pre设置为NULL,在curr不为空的情况下定义next指针,之后迭代逐次向后修改链表中的指针。
3. 在递归算法中,最后一句p=rest保证rest一直指向反转链表的头部,不会改变,还没理解这个究竟是怎样做到的。
参考文章:
http://www.leetcode.com/2010/04/reversing-linked-list-iteratively-and.html#comment-23502
相关文章推荐
- 链表反转的递归和非递归算法
- 链表反转的递归和非递归算法
- 单向链表反转(循环和递归)
- 反转链表(递归与非递归)
- 单链表反转(非递归java实现)
- 链表反转的递归和非递归实现方式
- 面试中常见链表问题12:单链表反转(递归)
- C/C++面试程序题(一)——字符串反转、链表反转的递归、非递归实现
- 续:一个带头结点的单链表反转(递归)
- 使用递归和非递归方式反转单向链表
- 【链表】非递归过程以O(N)反转单链表
- 链表反转C实现(递归与循环)
- 单链表逆序的递归与非递归算法
- 递归实现链表反转
- 反转链表[递归,非递归]
- 单链表反转(递归和非递归)
- 单链表逆序的递归与非递归算法
- java非递归实现单链表反转
- 反转链表的迭代实现和递归实现
- 链表的建立与反转(递归反转和非递归反转)