LeetCode每日一题:翻转链表部分

问题描述

Reverse a linked list from position m to n. 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 m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.

问题分析

翻转链表m到n之间的节点,要求只能在一次循环内完成,不能使用额外空间,所以不能使用栈来翻转,通过交换节点进行翻转

代码实现

public ListNode reverseBetween(ListNode head, int m, int n) {
        if (head == null) return null;
        ListNode preHead = new ListNode(0);
        preHead.next = head;//保留最初的head
        ListNode preStart = preHead;
        ListNode start = head;
        for (int i = 1; i < m; i++) {
            preStart = start;
            start = start.next;
        }//find m position
        for (int i = 0; i < n - m; i++) {
            ListNode temp = start.next;
            start.next = temp.next;
            temp.next = preStart.next;
            preStart.next = temp;
        }
        return preHead.next;
    }

你可能感兴趣的:(LeetCode每日一题:翻转链表部分)