forked from rost0413/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSwap_Nodes_in_Pairs.cpp
More file actions
62 lines (53 loc) · 1.22 KB
/
Swap_Nodes_in_Pairs.cpp
File metadata and controls
62 lines (53 loc) · 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/*
Author: Weixian Zhou, ideazwx@gmail.com
Date: Jul 26, 2012
Problem: Swap Nodes in Pairs
Difficulty: easy
Source: http://www.leetcode.com/onlinejudge
Notes:
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.
Solution:
*/
#include <vector>
#include <set>
#include <climits>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <cmath>
#include <cstring>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
class Solution {
public:
ListNode *swapPairs(ListNode *head) {
/* new head to make operation simpler */
ListNode *newhead = new ListNode(0);
ListNode *cur = newhead;
newhead->next = head;
while (cur->next != NULL && cur->next->next != NULL) {
ListNode *n0 = cur;
cur = cur->next;
ListNode *n1 = cur;
cur = cur->next;
ListNode *n2 = cur;
n0->next = n2;
n1->next = n2->next;
n2->next = n1;
cur = n1;
}
head = newhead->next;
delete newhead;
return head;
}
};