lintcode 36 Reverse Linked List II

题目描述

Description
Reverse a linked list from position m to n.

  • Given m, n satisfy the following condition: 1 ≤ m ≤ n ≤ length of list.

Example
Given 1->2->3->4->5->NULL, m = 2 and n = 4, return 1->4->3->2->5->NULL.

Challenge
Reverse it in-place and in one-pass

思路

之前写过链表翻转,是翻转整个链表的,当然这里改了一部分,只不过只需要加几步就行了。

  1. 找到开始翻转的节点,然后开始断开链表,形成两个链表,一个是翻转位置前面的链表,一个是翻转位置开始的链表。
  2. 链表翻转,不过这里跟之前有点不同,我是采用,将每个节点依次断开,插入到前面的链表的最后一个位置中。
  3. 找到翻转后的最后节点,进行拼接。

感觉这个思路说着可能不好理解
在这里插入图片描述
链表:1->2->3->4->5->6->7->null m:3   n:6
得到的链表应该是:1->2->6->5->4->3->7->null
下面是步骤

  1. 1->2->null, 3->4->5->6->7->null
  2. 1->2->3->null, 4->5->6->7->null
  3. 1->2->4->3->null, 5->6->7->null
  4. 1->2->5->4->3->null, 6->7->null
  5. 1->2->6->5->4->3->null, 7->null
  6. 1->2->6->5->4->3->7->null

这样比较容易理解了吧

代码

public ListNode reverseBetween(ListNode head, int m, int n) {
        // write your code here
        /*
        新建一个链表result,用链表next节点表示head初始头结点,head再等于result,
        避免m = 1时不进行反转。
        */
        ListNode result = new ListNode(0);
        result.next = head;
        head = result;
        /*
        找到第一个开始翻转的节点
         */
        while (m > 1) {
            head = head.next;
            m--;
            n--;
        }
        ListNode start = head.next;
        ListNode temp;
        head.next = null;
        /*
        开始翻转
         */
        while (n > 0) {
            temp = start;
            start = start.next;
            temp.next = head.next;
            head.next = temp;
            n--;
        }
        /*
        找到第一个链表最后一个节点,并进行连接
         */
        while (head.next != null) {
            head = head.next;
        }
        head.next = start;
        return result.next;
    }

猜你喜欢

转载自blog.csdn.net/qq_35464543/article/details/83151517