My Java Solution


  • 0

    Share a little bit about my idea. Feel free to discuss with me.

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode swapPairs(ListNode head) {
            if(head==null){
                return null;
            }
            if(head.next==null){
                return head;
            }
            ListNode start= new ListNode(0);
            ListNode cur = head;
            ListNode cur2 = head.next;
            ListNode tmp = cur2;
            start.next = cur;
            ListNode cur0 = start;
            while(cur2!=null){
                //ListNode temp = cur;
                cur0.next = cur2;
                cur.next = cur2.next;
                cur2.next = cur;
                cur0 = cur;
                cur = cur.next;
                if(cur==null){
                    break;
                }
                cur2 = cur.next;
            }
            return tmp;
        }
    }
    

Log in to reply
 

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