问题描述
给定单链表,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;
}