[Leetcode] Reverse Linked List II

Reverse Linked List II 题解

题目来源:https://leetcode.com/problems/reverse-linked-list-ii/description/


Description

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

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.

Solution


class Solution {
public:
    ListNode* reverseBetween(ListNode* head, int m, int n) {
        if (head == NULL || head -> next == NULL || m == n)
            return head;
        ListNode *tempHead = new ListNode(0);
        tempHead -> next = head;
        ListNode *preNode = tempHead, *frontNode = head;
        int pos = 1;
        while (pos < m) {
            preNode = frontNode;
            frontNode = frontNode -> next;
            pos++;
        }
        ListNode *backNode = frontNode -> next;
        ListNode *nextNode = backNode -> next;
        while (pos < n) {
            backNode -> next = frontNode;
            frontNode = backNode;
            backNode = nextNode;
            if (nextNode == NULL) {
                break;
            }
            nextNode = nextNode -> next;
            pos++;
        }
        preNode -> next -> next = backNode;
        preNode -> next = frontNode;
        return tempHead -> next;
    }
};


解题描述

这道题题意是给出一个链表,要求将其中第m~n个节点进行反转。考虑的办法还是跟反转整个链表差不多,但是要考虑多一点是,要保存m-1位前的链表位置(即preNode)以及n+1位后的链表位置(即backNode),以便后续连接成新的链表。而当m = 1的时候,preNode处没有节点,考虑到这个情况,解法中加入了一个临时链表头tempHead以保证preNode的存在并且便于后续直接获取新的链表头即tempHead -> next

posted @ 2018-01-29 15:05  言何午  阅读(110)  评论(0编辑  收藏  举报