# [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.`

## Solution

``````public class Solution {
public ListNode swapNodes(ListNode head, int v1, int v2) {
ListNode dummy = new ListNode(0);
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;
}
}``````