leetcode :24 题。

如果最后只有一个元素,也就是单数 忽略。


C#:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int val=0, ListNode next=null) {
 *         this.val = val;
 *         this.next = next;
 *     }
 * }
 */
public class Solution {
    public ListNode SwapPairs(ListNode head) {
        var dummyHead = new ListNode();
        dummyHead.next = head;
        var cur = dummyHead;
        while(cur.next != null && cur.next.next != null)
        {
            var temp = cur.next;
            var temp1 = cur.next.next.next;

            cur.next = cur.next.next;
            cur.next.next = temp;
            temp.next = temp1;
            cur = cur.next.next;
        }
        return dummyHead.next;
    }
}