单链表倒序的递归与非递归实现

在各大公司面试中,通常会遇到的最基本的算法题之一是单链表的倒序问题。在此仅介绍最常用的且复杂度相对较低的方法。

leetcode中同样也有这道题:Reverse a singly linked list

答案:http://www.programcreek.com/2014/05/leetcode-reverse-linked-list-java/

对于非递归的实现方法:使用三个临时指针依次遍历。

具体代码如下:

1. 首先给出节点类

 1 class Node
 2 {
 3 public:
 4     Node(string curData,Node *mNext){
 5         data = curData;
 6         next = mNext;
 7     }
 8     ~Node(){
 9         cout<<data<<"析构函数"<<endl;
10     }
11 public:
12     string data;
13     Node *next;
14     
15 };

2. 非递归实现单链表倒序:

Node *listInvert(Node *head)
{
    Node *p1,*p2,*p3;
    p1 = head;
    p2 = p1->next;

    while(p2)
    {
        p3 = p2->next;
        p2->next = p1;
        p1 = p2;
        p2 = p3;
    }
    head->next = NULL;//注意:此时头指针改变

    return p1;
}

3. 递归实现逆序:

//递归调用
Node * reverseRecursion(Node *head)
{
    if (head == NULL||head->next == NULL)
    {
        return head;
    }

    Node *second = head->next;
    head->next = NULL;

    Node *rest = reverseRecursion(second);

    second->next = head;

    return rest;
}

4. 方法调用:

void printNode(Node *root)
{
    while(root != NULL)
    {
        cout<<root->data<<" ";
        root = root->next;
    }
    cout<<endl;
}
int main(int argc, char const *argv[])
{
    Node *four = new Node("D",NULL);
    Node *third = new Node("C",four);
    Node *sec = new Node("B",third);
    Node *head = new Node("A",sec);
    
    // cout<<"原始链表顺序:";
    // printNode(head);
    // Node *result = listInvert(head);
    // cout<<"倒序结果:";
    // printNode(result);

    cout<<"原始链表顺序:";
    printNode(head);
    Node *result = reverseRecursion(head);
    cout<<"递归 倒序结果:";
    printNode(result);
    cout<<endl;


    delete head;
    delete sec;
    delete third;
    head = NULL;
    sec = NULL;
    third = NULL;
    return 0;
}

5. 结果

原始链表顺序:A B C D 
递归 倒序结果:D C B A 

A析构函数
B析构函数
C析构函数

 6. 源码 algorithm/list_invert.cpp

posted on 2017-04-18 15:28 bky2016 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/calence/p/6728065.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值