24. Swap Nodes in Pairs

reverse linked list升级版

1.recustion:

和中序遍历的递归写法有点像,先定义n,然后让head.next递归去得到结果,最后让n.next=head连接整理好的链表,过程见图。

public ListNode swapPairs(ListNode head) {
    if ((head== null) || (head.next) == null) {
        return head;
    }
    ListNode n = head.next;
    head.next = swapPairs(head.next.next);
    n.next = head;
    return n;
}

2.iteration:

见图顺序,dummy的作用是创建新的链表头,返回结果的时候用,point是取节点的基础。

public ListNode swapPairs(ListNode head) {
    ListNode dummy = new ListNode(0);
    dummy.next = head;
    ListNode point = dummy;
    while (point.next != null && point.next.next != null) {
        ListNode s1 = point.next;
        ListNode s2 = point.next.next;
        point.next = s2;
        s1.next = s2.next;
        s2.next = s1;
        point = s1;
    }
    return dummy.next;
}

results matching ""

    No results matching ""