zoukankan      html  css  js  c++  java
  • Leetcode92_反转链表II

    题目地址

    链表部分反转

    • 憨比解法,找到反转段的pre,反转中间段的同时记录尾节点,再接上后面一段
    • 优秀解法,中间段的反转用头插法的思路
    • 注意用个dummy头结点会比较方便处理边界

    code1

    class Solution {
        public ListNode reverseBetween(ListNode head, int m, int n) {
            ListNode dummy=new ListNode(0);
            dummy.next=head;
            ListNode pre=dummy;
            int id=1;
            while(id<m){
                pre=head;
                head=head.next;
                id++;
            }
            ListNode newHead=null;
            ListNode newTail=null;
            for(int i=m;i<=n;i++){
                ListNode tmp=head;
                head=head.next;
                tmp.next=newHead;
                newHead=tmp;
                if(newTail==null){
                    newTail=tmp;
                }
            }
            pre.next=newHead;
            newTail.next=head;
            return dummy.next;
        }
    }
    

    code2

    class Solution {
        public ListNode reverseBetween(ListNode head, int m, int n) {
            ListNode dummy=new ListNode(0);
            dummy.next=head;
            ListNode pre=dummy;
            for(int i=1;i<m;i++){
                pre=pre.next;
            }
            head=pre.next;
            for(int i=m;i<n;i++){
                //头插法,插入后tmp是中间段的头结点
                //翻转pre,a[m...n]只需要将a[m+1...n]依次插入到pre后面
                ListNode tmp=head.next;
                //head指向当前节点的上一个节点,即每次要头插的就是head.next
                head.next=head.next.next;
                //头插法
                tmp.next=pre.next;
                pre.next=tmp;
            }
            return dummy.next;
        }
    }
    
  • 相关阅读:
    mysql升级大致
    初始化配置文件的使用:/etc/my.cnf
    mysql用户管理
    MySql的逻辑结构(抽象结构)与物理结构
    5.7与5.6版本在部署方面的改变
    MySql服务器进程结构
    MySql服务器构成 --实列
    mysql客户端与服务器端模型
    RDBMS和NoSQL区别即主流sql
    MySql基本操作
  • 原文地址:https://www.cnblogs.com/zxcoder/p/12295254.html
Copyright © 2011-2022 走看看