Week13: Swap Nodes in Pairs
Difficulty:Medium
1.Problem
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4
, you should return the list as 2->1->4->3
.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
2.Algorithm
1.首先,创建一个指针空间
start
,而且start->next = head
;2.然后,创建指针
pointer = start
,创建指针a = pointer->next
,
以及b = pointer->next->next
3.然后将
pointer->a->b->b.next
变为pointer->b->a->b.next
4.做完3的变换后,
pointer = a
。如此循环下去直到链表的终点。
3.Solution
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode *start = new ListNode(0);
start->next = head;
ListNode *a, *b, *pointer = start;
while(pointer->next != NULL && pointer->next->next != NULL) {
a = pointer->next;
b = pointer->next->next;
a->next = b->next;
b->next = a;
pointer->next = b;
pointer = a;
}
return start->next;
}
};