LeetCode 92
Reverse Linked List II
Problem Description:
给出两个值m和n,将链表中从第m到n个结点部分进行翻转,其余结点不变。
具体的题目信息:
https://leetcode.com/problems/reverse-linked-list-ii/description/Solution:
解题思路
本题用两个栈实现,临时栈temp
存储需要进行翻转的结点的值,结果栈re
存储按照原顺序的结点的值。有几种情况需要考虑,从头开始进行翻转和从中间开始进行翻转,一直翻转到结尾和翻转到链表中间。编程实现
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
if (head == NULL)
return head;
if (head->next == NULL)
return head;
if (m == n)
return head;
stack<int> re; //输出栈
stack<int> temp; //临时栈,存储进行翻转的值
int count = 1;
ListNode* p = head;
while(p) {
//若从头开始翻转则一开始就把链表的值push进栈temp
if (m == 1&&count<= n) {
temp.push(p->val);
//需要判断是否整条链表都进行翻转,如果是,直接将temp栈中值push进输出栈re
if (p->next == NULL) {
while(!temp.empty()) {
re.push(temp.top());
temp.pop();
}
}
} else if (count<m) {
//若不是从头开始翻转,则把小于m的结点值push进结果栈
re.push(p->val);
} else if (count>= m&&count<= n) {
//将需要进行翻转的值push进临时栈
temp.push(p->val);
//判断是否翻转到尾部,如果是,将临时栈中的值push进结果栈
if (p->next == NULL) {
while(!temp.empty()) {
re.push(temp.top());
temp.pop();
}
}
} else {
//若没有翻转到结尾,则遇到第一个不需要进行翻转的值时要先把临时栈中的值push进结果栈,再对剩余的结点进行处理
if (count==n+1) {
while(!temp.empty()) {
re.push(temp.top());
temp.pop();
}
}
re.push(p->val);
}
count++;
p = p->next;
}
ListNode* t = createList(re);
return t;
}
//根据栈中的值使用头插法来建立链表
ListNode* createList(stack<int> t) {
ListNode* p = new ListNode(t.top());
t.pop();
p->next = NULL;
ListNode* q;
while(!t.empty()) {
q = new ListNode(t.top());
q->next = p;
p = q;
t.pop();
}
return q;
}
};