LeetCode/solutions/24. Swap Nodes in Pairs.md

32 lines
1.1 KiB
Markdown
Raw Normal View History

2018-12-19 02:01:00 +00:00
# [24. Swap Nodes in Pairs](https://leetcode.com/problems/swap-nodes-in-pairs/)
# 思路
将一个链表两个两个地进行翻转。
为了方便我们可以设置一个头结点head_node。用p1指向当前需要翻转的第一个节点p2指向当前需要翻转的第二个节点并用pre指向p1的前一个节点。
然后交换p1、p2两个节点即可再将指针向右移进行下一次翻转。
时间复杂度O(n)空间复杂度O(1)
# C++
``` C++
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(head == NULL || head -> next == NULL) return head;
ListNode *head_node = new ListNode(0);
head_node -> next = head;
ListNode *pre = head_node, *p1 = head, *p2 = head -> next;
while(p2 != NULL){
// 翻转
p1 -> next = p2 -> next;
p2 -> next = p1;
pre -> next = p2;
// 指针右移,准备进行下一次翻转
pre = p1;
p1 = pre -> next;
if(p1 == NULL) break; // 到链尾了
p2 = p1 -> next;
}
return head_node -> next;
}
};
```