Reverse Linked List II

来源:互联网 发布:淘宝客推广加权重吗 编辑:程序博客网 时间:2024/06/02 00:37

一、问题描述

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->NULLm = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given mn satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.

二、思路

首先,定义一个头结点,指向head;然后循环找到m-1位置作为first,再执行循环逆置链表,直到n位置结束,当到达n时,用last指向最后一个节点;最后将first节点的下个节点连接到第m个节点位置,完成逆置,最后返回头结点的下一个节点。

三、代码

/** * 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 *dummy = new ListNode(0),;        dummy->next = head;        ListNode*cur = dummy, *prev = NULL, *first = NULL, *last = NULL;        for (int i = 0; i <= n; i++) {            if (i == m - 1) {                first = cur;                cur = cur->next;            } else if (i > m - 1) {                if (i == n) last = cur;                ListNode *temp = cur;                cur = cur->next;                temp->next = prev;                prev = temp;            } else {                cur = cur->next;            }        }        first->next->next = cur;        first->next = last;        return dummy->next;}};


0 0