反转链表2

2019-01-30  本文已影响0人  小白学编程

反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。

说明:
1 ≤ m ≤ n ≤ 链表长度。

示例:

输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 1->4->3->2->5->NULL

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        ListNode dumpy = new ListNode(0);
        dumpy.next = head;
        ListNode pre = null, first = null, temp = dumpy;
        int index = 0;

        while (true) {
            if (index == m - 1) {
                pre = temp;
            }

            if (index == m) {
                first = temp;
                break;
            }

            index++;
            temp = temp.next;
        }
        ListNode last = null, later = null;
        while (true) {
            if (index == n) {
                last = temp;
            }

            if (index == n + 1) {
                later = temp;
                break;
            }

            ListNode behind = temp.next;
            temp.next = later;
            later = temp;
            temp = behind;
            index++;

            
        }

        pre.next = last;
        first.next = later;
        return dumpy.next;
    
    }
}
上一篇下一篇

猜你喜欢

热点阅读