题目描述:
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.
Given 1->2->3->4->null
and
v1 = 2
, v2 = 4
.
Return 1->4->3->2->null
.
凡是有可能head会加入的题目,我觉得都可以用dummy head这个好东西。比如这题,v1有可能就是1的情况下,用了dummy head,就可以把这种情况当做general case处理啦。这题需要考虑的特殊情况有:
1. v1或者v2找不到
2. v1和v2紧挨着:这里我又分了两种情况 -- v1在v2前面,以及v1在v2后面
3. general swap case
Mycode(AC = 21ms):
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
/**
* @param head a ListNode
* @oaram v1 an integer
* @param v2 an integer
* @return a new head of singly-linked list
*/
ListNode* swapNodes(ListNode* head, int v1, int v2) {
// Write your code here
ListNode *dummy = new ListNode(0);
dummy->next = head;
ListNode *ptr1 = dummy, *ptr2 = dummy;
while (ptr1->next && ptr1->next->val != v1) {
ptr1 = ptr1->next; // 2
}
while (ptr2->next && ptr2->next->val != v2) {
ptr2 = ptr2->next; // 4
}
// if can't find one of the values
if (!ptr1->next || !ptr2->next) {
return head;
}
// if ptr1 is neighbor of ptr2
else if (ptr1->next->val == ptr2->val) {
ptr1->next = ptr2->next;
ptr2->next = ptr1->next->next;
ptr1->next->next = ptr2;
}
// if ptr2 is before ptr1
else if (ptr2->next->val == ptr1->val) {
return swapNodes(head, v2, v1);
}
else { // other normal cases
ListNode *next1 = ptr1->next->next, // 3
*next2 = ptr2->next->next, // null
*tmp = ptr1->next; // 2
ptr1->next = ptr2->next; //
ptr1->next->next = next1;
ptr2->next = tmp;
ptr2->next->next = next2;
}
return dummy->next;
}
};