File tree Expand file tree Collapse file tree 1 file changed +57
-1
lines changed Expand file tree Collapse file tree 1 file changed +57
-1
lines changed Original file line number Diff line number Diff line change @@ -70,7 +70,7 @@ https://leetcode-cn.com/problems/swap-nodes-in-pairs/
70
70
71
71
## 代码
72
72
73
- * 语言支持:JS,Python3
73
+ * 语言支持:JS,Python3, Go, PHP
74
74
75
75
``` js
76
76
/**
@@ -127,6 +127,62 @@ class Solution:
127
127
return _next
128
128
```
129
129
130
+ Go Code:
131
+
132
+ ``` go
133
+ /* *
134
+ * Definition for singly-linked list.
135
+ * type ListNode struct {
136
+ * Val int
137
+ * Next *ListNode
138
+ * }
139
+ */
140
+ func swapPairs (head *ListNode ) *ListNode {
141
+ if head == nil || head.Next == nil {
142
+ return head
143
+ }
144
+
145
+ next := head.Next
146
+ head.Next = swapPairs (next.Next ) // 剩下的节点递归已经处理好, 拼接到前 2 个节点上
147
+ next.Next = head
148
+ return next
149
+ }
150
+ ```
151
+
152
+ PHP Code:
153
+
154
+ ``` php
155
+ /**
156
+ * Definition for a singly-linked list.
157
+ * class ListNode {
158
+ * public $val = 0;
159
+ * public $next = null;
160
+ * function __construct($val = 0, $next = null) {
161
+ * $this->val = $val;
162
+ * $this->next = $next;
163
+ * }
164
+ * }
165
+ */
166
+ class Solution
167
+ {
168
+
169
+ /**
170
+ * @param ListNode $head
171
+ * @return ListNode
172
+ */
173
+ function swapPairs($head)
174
+ {
175
+ if (!$head || !$head->next) return $head;
176
+
177
+ /** @var ListNode $next */
178
+ $next = $head->next;
179
+ $head->next = (new Solution())->swapPairs($next->next); // 递归已经将后面链表处理好, 拼接到前面的元素上
180
+ $next->next = $head;
181
+ return $next;
182
+ }
183
+ }
184
+ ```
185
+
130
186
** 复杂度分析**
131
187
- 时间复杂度:$O(N)$
132
188
- 空间复杂度:$O(1)$
You can’t perform that action at this time.
0 commit comments