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;
}

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理