Reverse Linked List II
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,
return 1->4->3->2->5->NULL.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
解题思想:运用栈的先进后出思想来存储需要reverse的链表部分。
/**
* 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) {
ListNode* pre;
ListNode* next;
int i=0;
ListNode* tmphead=new ListNode(-1);
tmphead->next=head;
ListNode* p=tmphead;
stack<int> tmp;
while(p!=NULL){
if(i==m-1)
pre=p; //前驱节点
if(i>=m&&i<=n)
tmp.push(p->val);
if(i==n)
next=p->next; //反转链表之后的节点
i++;
p=p->next;
}
while(!tmp.empty()){
ListNode* t=new ListNode(tmp.top());
pre->next=t;
pre=t;
tmp.pop();
}
pre->next=next;
return tmphead->next;
}
};