题目描述
Reverse a linked list from position m to n. Do it in one-pass.
Note: 1 ≤ m ≤ n ≤ length of list.
Example:
Input: 1->2->3->4->5->NULL, m = 2, n = 4
Output: 1->4->3->2->5->NULL
/**
* 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* reverseBetween(ListNode* head, int m, int n) {
ListNode *tmpHead = new ListNode();
tmpHead->next = head;
ListNode *pre = tmpHead;
for(int i = 1; i < m; i++){
pre = pre->next;
}
head = pre->next;
for(int i = m; i < n; i++){
ListNode *post = head->next;
head->next = post->next;
post->next = pre->next;
pre->next = post;
}
return tmpHead->next;
}
其中,pre 这个指针一直不动,head 和 post 逐步后移,直至 i < n 为止。完成并返回 tmpHead->next 。
网友评论