栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

算法-翻转链表

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

算法-翻转链表

翻转链表

class Solution {
    public ListNode reverseList(ListNode head) {
      if (head == null) {
         return null;
      }
        // 1 -> 2 -> 3 -> 4 -> 5
        //prev = 1
        // current = 2;
      ListNode prev = head;
      ListNode current = head.next;
        // 1  2 -> 3 -> 4 -> 5
        // prev = 1
        // current = 2;
      prev.next = null;
      while (current != null) {
          // First time
          
          // Second time
          
          // third time
          
          // fourth time
          
          ListNode next = current.next;
          current.next = prev;
          prev = current;
          current = next;
      }
        //exit
        //return prev = 5
      return prev;
    }
}

翻转链表(指定区域内链表翻转)

class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        if (head == null || m >= n) {
            return head;
        }
        ListNode dummy = new ListNode(-1);
        //增加一个前置节点
        dummy.next = head;
        head = dummy;
        //m 位置设置为head节点
        for (int i = 1; i < m; i++) {
            head = head.next;
        }
        ListNode prevM = head;
        ListNode mNode = head.next;
        ListNode nNode = mNode;
        ListNode postN = nNode.next;
        //区域内翻转
        // nNode => prev;
        //postN => current
        for(int i = m; i < n; i++) {
            
            ListNode next = postN.next;
            postN.next = nNode;
            nNode = postN;
            postN = next;
        }
        //调整整个链表
        mNode.next = postN;
        prevM.next = nNode;
        return dummy.next;
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/934784.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号