[LintCode] Swap Two Nodes in Linked List

linspiration

Problem

Given a linked list and two values v1 and v2. Swap the two nodes in the linked list with values v1 and v2. It's guaranteed there is no duplicate values in the linked list. If v1 or v2 does not exist in the given linked list, do nothing.

Notice

You should swap the two nodes with values v1 and v2. Do not directly swap the values of the two nodes.

Example

Given 1->2->3->4->null and v1 = 2, v2 = 4.

Return 1->4->3->2->null.

Note

建立dummy结点,指向head(可能要对head进行操作)。
找到值为v1和v2的结点(设为n1,n2)的前结点p1, p2;
若p1和p2其中之一为null,则n1和n2其中之一也一定为null,返回头结点即可。
正式建立n1,n2,以及对应的next结点x1,x2,然后:
先分析n1和n2是相邻结点的两种情况:n1是n2的前结点,或n2是n1的前结点;
再分析非相邻结点的一般情况。
返回dummy.next,结束。

Solution

public class Solution {
    public ListNode swapNodes(ListNode head, int v1, int v2) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode p1 = null, p2 = null, cur = dummy;
        while (cur.next != null) {
            if (cur.next.val == v1) p1 = cur;
            else if (cur.next.val == v2) p2 = cur;
            cur = cur.next;
        }
        if (p1 == null || p2 == null) return dummy.next;
        ListNode n1 = p1.next, n2 = p2.next, x1 = n1.next, x2 = n2.next;
        if (p1.next == p2) {
            p1.next = n2;
            n2.next = n1;
            n1.next = x2;
        }
        else if (p2.next == p1) {
            p2.next = n1;
            n1.next = n2;
            n2.next = x1;
        }
        else {
            p1.next = n2;
            n2.next = x1;
            p2.next = n1;
            n1.next = x2;
        }
        return dummy.next;
    }
}
阅读 1.8k

Road to Glory
對酒當歌,人生幾何? 譬如朝露,去日苦多。
161 声望
53 粉丝
0 条评论
161 声望
53 粉丝
文章目录
宣传栏