Java Solution can be used in K Group reverse


  • 0
    R
    static int steps = 2;
        public ListNode swapPairs(ListNode head) {
            if(head==null){
                return null;
            }
    
            ListNode newHeader = head;
            ListNode start = head;
            while(head.next!=null){
                ListNode end = start;
                for(int i =0; i<steps-1;i++){
                    end=end.next;
                    if(end==null){
                        return newHeader;
                    }
                }
    
                if(newHeader == head){
                    start = head;
                    swap(start,end);
                    newHeader=end;
                }
                else{
                    head.next= swap(start,end);
                }
                head=start;
                start = head.next;
            }
            return newHeader;
    
        }
    
        private ListNode swap(ListNode head, ListNode end){
            ListNode current = head;
            ListNode pre = current;
            current = current.next;
            while(current!=end){
                ListNode next = current.next;
                current.next=pre;
                pre=current;
                current = next;
            }
            head.next=end.next;
            end.next=pre;
            return end;
        }

Log in to reply
 

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