码迷,mamicode.com
首页 > 其他好文 > 详细

92. Reverse Linked List II

时间:2018-09-26 12:19:05      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:int   span   next   解答   新建   直接   ever   链表   index   

一、题目

  1、审题

技术分享图片

 

  2、分析

    给出一个整数链表,翻转从第 m 到 n 的所有节点(m <= n)。

 

二、解答

  1、思路:  

    方法一、用到了 6 个指针变量

      ①、新建一个伪头结点,指向 head,且一指针向前移动直到 index == m;

      ②、若 m <= index <= n ,则将之间的节点插入一个新链表的头部,且记录此链表的头部尾部。

      ③、将 ①与②的链表拼接,并将 index > n 的剩下的节点链表拼接在尾部。

public ListNode reverseBetween(ListNode head, int m, int n) {
        
        ListNode fakeHead = new ListNode(0);
        fakeHead.next = head;
        ListNode pre = fakeHead;
        ListNode cur = head;
        ListNode head2 = null;
        ListNode flagNode = null;
        int index = 1;
        while(index <= n) {
            
            if(index < m) {
                pre.next = cur;
                pre = pre.next;
                cur = cur.next;
            }
            else {
                ListNode tmp = cur.next;    //    翻转节点
                if(head2 == null)        // 记录尾部
                    flagNode = cur;
                cur.next = head2;
                head2 = cur;
                cur = tmp;
            }
            index++;
        }
        
        pre.next = head2;
        if(flagNode != null)
            flagNode.next = cur;
        
        return fakeHead.next;
    }

 

   方法二、

    使用 4 个指针变量,直接在原链表中进行节点的交换。

public ListNode reverseBetween2(ListNode head, int m, int n) {
    
        if(head == null)    return null;
        
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode pre = dummy;
        for (int i = 0; i < m-1; i++)     // pre 指向第 m-1 个
            pre = pre.next;
        
        ListNode start = pre.next;    // 第 m 个
        ListNode then = start.next;    // 第 m + 1 个
        
        for (int i = 0; i < n-m; i++) {  // 交换
            start.next = then.next;
            then.next = pre.next;
            pre.next = then;
            then = start.next;
        }
        
        return dummy.next;
    }

 

92. Reverse Linked List II

标签:int   span   next   解答   新建   直接   ever   链表   index   

原文地址:https://www.cnblogs.com/skillking/p/9706119.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!