C# 122ms Solution


  • 0
    L
    /**
     * 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 SwapPairs(ListNode head) {
            if (head == null) return null;
            ListNode p, p1, p2;
            p1 = head;
            p2 = head.next;
            if (p2 != null)
            {
                p = p2.next;
                p2.next = p1;
                p1.next = p;
                p = p1;
                head = p2;
            }
            else
                return head;
            while (p != null)
            {
                p1 = p.next;
                if (p1 == null) return head;
                p2 = p1.next;
                if (p2 == null) return head;
                p1.next = p2.next;
                p2.next = p1;
                p.next = p2;
                p = p1;
            }
            return head;
        }
    }

Log in to reply
 

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