您的位置:首页 > 其它

单链表反转递归与非递归算法

2012-08-08 20:14 274 查看
1. 代码如下:

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: