• 92. Reverse Linked List II


    一、题目

      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;
        }
  • 相关阅读:
    [angularjs] angularjs系列笔记(五)Service
    [android] 隐式意图的配置
    [android] 隐式意图激活另外一个activity
    [angularjs] angularjs系列笔记(四)过滤器
    [android] 显示意图激活另外一个activity
    [android] smartimageview&常见的开源代码
    [angularjs] angularjs系列笔记(四)控制器
    [android] 上传文件到服务器
    [android] 异步http框架与实现原理
    [android] 采用httpclient提交数据到服务器
  • 原文地址:https://www.cnblogs.com/skillking/p/9706119.html
Copyright © 2020-2023  润新知