Create 24. Swap Nodes in Pairs.md

This commit is contained in:
唐树森 2018-12-19 10:01:00 +08:00 committed by GitHub
parent 6817071839
commit 4558314734
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -0,0 +1,31 @@
# [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;
}
};
```