mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
Create 24. Swap Nodes in Pairs.md
This commit is contained in:
parent
6817071839
commit
4558314734
31
24. Swap Nodes in Pairs.md
Normal file
31
24. Swap Nodes in Pairs.md
Normal 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;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
```
|
Loading…
Reference in New Issue
Block a user