[LeetCode]24. 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.node

Example:code

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

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;
}
相關文章
相關標籤/搜索