【reverse-linked-list-ii】

来源:互联网 发布:时间煮雨 知乎 编辑:程序博客网 时间:2024/06/05 02:45

Reverse a linked list from position m ton. Do it in-place and in one-pass.

For example:
Given1->2->3->4->5->NULL, m = 2 and n = 4,

return1->4->3->2->5->NULL.

Note: 
Given mn satisfy the following condition:

1 ≤ m ≤ n ≤ length of list.


指定位置(m,n)部分进行翻转

思路:翻转m-n之间的部分,将链表分为三部分,最后再重新拼接;

#include <iostream>#include <stdio.h>#include <vector>#include <iterator>#include <map>using namespace std;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 NULL;}ListNode* phead = new ListNode(-1);phead->next = head;ListNode* p = phead;for (int i=0; i<m-1; i++){p = p->next;}ListNode* firstTail = p;ListNode* secondTail = p->next;ListNode* pre = NULL;ListNode* node = secondTail;//进行链表的逆转for (int i=0; i<=n-m; i++){ListNode* tmp = node->next;node->next = pre;pre = node;node = tmp;}firstTail->next = pre;secondTail->next = node;return phead->next;}};


原创粉丝点击