Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 8b0539e

Browse files
Merge pull request youngyangyang04#629 from qxuewei/master
添加 19.删除链表的倒数第N个节点 Swift版本 & 添加 24. 两两交换链表中的节点 Swift版本
2 parents c6e0a1b + 3e75414 commit 8b0539e

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

‎problems/0019.删除链表的倒数第N个节点.md‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,31 @@ fun removeNthFromEnd(head: ListNode?, n: Int): ListNode? {
204204
}
205205
```
206206

207+
Swift:
208+
```swift
209+
func removeNthFromEnd(_ head: ListNode?, _ n: Int) -> ListNode? {
210+
if head == nil {
211+
return nil
212+
}
213+
if n == 0 {
214+
return head
215+
}
216+
let dummyHead = ListNode(-1, head)
217+
var fast: ListNode? = dummyHead
218+
var slow: ListNode? = dummyHead
219+
// fast 前移 n
220+
for _ in 0 ..< n {
221+
fast = fast?.next
222+
}
223+
while fast?.next != nil {
224+
fast = fast?.next
225+
slow = slow?.next
226+
}
227+
slow?.next = slow?.next?.next
228+
return dummyHead.next
229+
}
230+
```
231+
207232
-----------------------
208233
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
209234
* B站视频:[代码随想录](https://space.bilibili.com/525438321)

‎problems/0024.两两交换链表中的节点.md‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -256,6 +256,27 @@ fun swapPairs(head: ListNode?): ListNode? {
256256
}
257257
```
258258

259+
Swift:
260+
```swift
261+
func swapPairs(_ head: ListNode?) -> ListNode? {
262+
if head == nil || head?.next == nil {
263+
return head
264+
}
265+
let dummyHead: ListNode = ListNode(-1, head)
266+
var current: ListNode? = dummyHead
267+
while current?.next != nil && current?.next?.next != nil {
268+
let temp1 = current?.next
269+
let temp2 = current?.next?.next?.next
270+
271+
current?.next = current?.next?.next
272+
current?.next?.next = temp1
273+
current?.next?.next?.next = temp2
274+
275+
current = current?.next?.next
276+
}
277+
return dummyHead.next
278+
}
279+
```
259280

260281

261282
-----------------------

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /