24. Swap Nodes in Pairs

Problem:
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.

5/1/2018 update:
First.next is like next in regular reverse. 
--------------------------------------------------------------------------------------------------------------------------------------------
Analysis:
Simple reverse linked list, but need to think about how to handle head. dummy不是随便一初始化就行了,需要考虑dummy的安置问题,不留死角。
Solution:
cur.next 把head给转移到了second, 然后cur就完成了任务,继续下一次reverse。
class Solution {
    public ListNode swapPairs(ListNode head) {
        if (head == null)
            return null;
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode prev = dummy;
        while (prev.next != null && prev.next.next != null) {
            ListNode first = prev.next, second = prev.next.next;
            first.next = second.next;
            second.next = first;
            prev.next = second;
            prev = first;
        }
        return dummy.next;
    }
}

评论

此博客中的热门博文

776. Split BST

663. Equal Tree Partition

532. K-diff Pairs in an Array