C# in-place n+n-m pass


  • 0
    Y
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     public int val;
     *     public ListNode next;
     *     public ListNode(int x) { val = x; }
     * }
     */
     //unit test [5] 1 1
    public class Solution {
        public ListNode ReverseBetween(ListNode head, int m, int n) {
            //split the list into three parts
            ListNode dummy=new ListNode(0);
            dummy.next=head;
            ListNode pre=dummy,runner=head;
            ListNode firEnd=null;
            for(int i=0;i<n;i++)
            {
                if(i == m - 1)
                    firEnd=pre;
                pre = pre.next;
            }
            var secondEnd = pre;
            var thirdHeder=secondEnd.next;
            secondEnd.next=null;
            var twoHead=firEnd.next;
            var twoHTemp=twoHead;
            firEnd.next=null;
            ListNode revPre=null;
            while(twoHead!=null)
            {
                var temp=twoHead.next;
                twoHead.next=revPre;
                revPre=twoHead;
                twoHead=temp;
            }
            firEnd.next=revPre;
            twoHTemp.next=thirdHeder;
            return dummy.next;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.