-
Notifications
You must be signed in to change notification settings - Fork 0
/
0024.两两交换链表中的节点.cpp
75 lines (71 loc) · 1.56 KB
/
0024.两两交换链表中的节点.cpp
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
63
64
65
66
67
68
69
70
71
72
73
74
75
/*
* @lc app=leetcode.cn id=24 lang=cpp
*
* [24] 两两交换链表中的节点
*
* https://leetcode-cn.com/problems/swap-nodes-in-pairs/description/
*
* algorithms
* Medium (61.75%)
* Likes: 336
* Dislikes: 0
* Total Accepted: 51.7K
* Total Submissions: 82.3K
* Testcase Example: '[1,2,3,4]'
*
* 给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
*
* 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
*
*
*
* 示例:
*
* 给定 1->2->3->4, 你应该返回 2->1->4->3.
*
*
*/
// @lc code=start
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
#include <vector>
using namespace std;
/* struct ListNode {
int val;
ListNode* next;
ListNode(int x)
: val(x)
, next(NULL)
{
}
}; */
class Solution {
public:
ListNode* swapPairs(ListNode* head)
{
if (head == nullptr) {
return nullptr;
}
ListNode* dummy_head = new ListNode(0);
dummy_head->next = head;
ListNode *r = dummy_head, *p = head, *q = p->next;
while (p != nullptr && q != nullptr) {
r->next = q;
p->next = q->next;
q->next = p;
r = p;
p = p->next;
if (p != nullptr)
q = p->next;
}
// delete 操作很耗时,所以不要 delete,直接返回
return dummy_head->next;
}
};
// @lc code=end