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;
    }
}

猜你喜欢

转载自www.cnblogs.com/zxcoder/p/12295254.html