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
.
分析:
因为这题里涉及到四个nodes,node1, node1Parent, node2, node2Parent, 然后有了这四个nodes,我们就可以对它们进行换位,但是这里有一种特殊情况node1是node2的parent,或者node2是node1的parent,需要单独处理一下。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
/**
* @param head a ListNode
* @oaram v1 an integer
* @param v2 an integer
* @return a new head of singly-linked list
*/
public ListNode swapNodes(ListNode head, int v1, int v2) {
if (head == null) return null;
if (v1 == v2) return head; int dummyValue = Math.abs(v1) + Math.abs(v2) + ; ListNode dummyHead = new ListNode(dummyValue);
dummyHead.next = head;
ListNode node1Parent = findNodeParent(dummyHead, v1);
ListNode node2Parent = findNodeParent(dummyHead, v2);
// if v1 or v2 doesn't exist, return
if (node1Parent == null || node2Parent == null) return head; ListNode node1 = node1Parent.next;
ListNode node2 = node2Parent.next;
// special case
if (node1.next == node2) {
node1Parent.next = node2;
node1.next = node2.next;
node2.next = node1;
} else if (node2.next == node1) { // special case
node2Parent.next = node1;
node2.next = node1.next;
node1.next = node2;
} else {
ListNode temp = node2.next;
node2.next = node1.next;
node1.next = temp;
node1Parent.next = node2;
node2Parent.next = node1;
}
return dummyHead.next;
} private ListNode findNodeParent(ListNode head, int v1) {
while (head.next != null) {
if (head.next.val == v1) {
return head;
} else {
head = head.next;
}
}
return null;
}
}
转载请注明出处:cnblogs.com/beiyeqingteng/