Using reverse and connect


  • 0
    Y
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     public int val;
     *     public ListNode next;
     *     public ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode ReverseBetween(ListNode head, int m, int n) {
        
            if( n==1 || n==0)
            {
                return head;
            }
            
            int i = 0;
            
            var result = head;
            
            var newHead = new ListNode(0); //for m==1 seniro
            newHead.next = head;
            //get the linked list get the start point:
            
            while(i < m - 1)
            {
                newHead = newHead.next;
                i += 1;
            }
            
            var reverseLinkList = newHead.next;
            var preConnect = newHead;
            
            //var preEnd = head;
            
            while(i < n)
            {
                newHead = newHead.next;
                i += 1;
            }
            
            var secStart = newHead.next;
            var reverseStart = newHead;
            
            //set to null before and end the reverse link list:
            reverseStart.next = null;
            preConnect.next = null;
            
            //reverse the sub linklist:
            ReverseLinkList(reverseLinkList);
            preConnect.next = reverseStart;
            reverseLinkList.next = secStart;
            
            if(m == 1)
            {
                return reverseStart;
            }
            
            return result;
        }
    
        public ListNode ReverseLinkList(ListNode head) {
            
                ListNode newHeader=null;
                
                while(head != null)
                {
                    var newHead=head.next;
                    head.next=newHeader;
                    newHeader=head;
                    head=newHead;
                }
                
                return newHeader;
            }
    }

Log in to reply
 

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