From 4558314734f1dee00cd6856059a19dcd9b48a30b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=94=90=E6=A0=91=E6=A3=AE?= <14021051@buaa.edu.cn> Date: Wed, 19 Dec 2018 10:01:00 +0800 Subject: [PATCH] Create 24. Swap Nodes in Pairs.md --- 24. Swap Nodes in Pairs.md | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 24. Swap Nodes in Pairs.md diff --git a/24. Swap Nodes in Pairs.md b/24. Swap Nodes in Pairs.md new file mode 100644 index 0000000..609e46e --- /dev/null +++ b/24. Swap Nodes in Pairs.md @@ -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; + } +}; +```