逆转单链表

问题描述

给定单链表,A0->A1->…->An->#, 求单链表的逆转,即#<-A0<-A1<-…<-An.

解决方案

本题有两种解决方法,就像回字有四种写法,这里就挑选最简单的写法——递归。
如果输入是1->2->3->4->null, 只需要首先逆转2->3->4->null为2<-3<-4, 然后将2指向1就好了;然后问题的规模变小,我们就可以故伎重演
递归的整体流程如下:
1.
1->2->3->4
1<->2<-3<-4
2.
2->3->4
2<->3<-4
3.
3->4
3<->4
4.
4
4 set newHead
代码面前无秘密,直接上代码。

/*************************************************************************
    > File Name: reverse_list.cpp
    > Author: Yuji CAO
    > Mail: yujicao@amazon.com
    > Created Time: 2016年08月12日 星期五 09时19分24秒
 ************************************************************************/

#include<iostream>
#include<vector>
#include<unordered_map>
#include<unordered_set>
#include<sstream>
#include<list>
#include<queue>
#include<stack>
#include<string>
#include<utility>
#include<algorithm>
using namespace std;
struct Node {
    int val;
    Node* next;
    Node(int val):val(val),next(nullptr){};
};

class LinearTable {
public:
    Node* reverseList(Node* head) {
        Node* newHead = nullptr;
        Node* tail = reverseInner(head, newHead);
        tail->next = nullptr;
        return newHead;
    }
    static Node* mkList(vector<int> data) {
        Node* head = new Node(data[0]);
        Node* ans = head;
        for (int i = 1; i < data.size(); ++i) {
            head->next = new Node(data[i]);
            head = head->next;
        }
        head->next = nullptr;
        return ans;
    }
    static void visit(Node* list) {
        while(list != nullptr) {
            cout<<list->val<<",";
            list=list->next;
        }
        cout<<endl;
    }
private:
    Node* reverseInner(Node* head, Node*& newHead) {
        if (head->next == nullptr) {
            newHead = head;
            return head;
        }
        Node* tail = reverseInner(head->next, newHead);
        tail->next = head;
        return head;
    }
};
int main() {
    LinearTable lt;
    int N = 0;
    cin>>N;
    vector<int> data;
    for (int i = 0; i < N; ++i) {
        int a;
        cin>>a;
        data.push_back(a);
    }
    Node* head = LinearTable::mkList(data);
    LinearTable::visit(head);
    LinearTable::visit(lt.reverseList(head));
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值