乐趣区

LeetCode24-Swap-Nodes-in-Pairs

Given a linked list, swap every two adjacent nodes and return its
head.

You may not modify the values in the list’s nodes, only nodes itself
may be changed.

Example:

Given 1->2->3->4, you should return the list as 2->1->4->3.

public ListNode swapPairs(ListNode head) {ListNode trueHead=new ListNode(0);
    trueHead.next=head;
    ListNode cur=trueHead;
    while(cur.next!=null && cur.next.next!=null){
        ListNode first=cur.next;
        ListNode second=cur.next.next;
        cur.next=second;
        first.next=second.next;
        second.next=first;
        cur=first; 
    }
    return trueHead.next;
}
退出移动版