mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
添加 19.删除链表的倒数第N个节点 Swift版本
This commit is contained in:
@ -204,6 +204,31 @@ fun removeNthFromEnd(head: ListNode?, n: Int): ListNode? {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Swift:
|
||||||
|
```swift
|
||||||
|
func removeNthFromEnd(_ head: ListNode?, _ n: Int) -> ListNode? {
|
||||||
|
if head == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if n == 0 {
|
||||||
|
return head
|
||||||
|
}
|
||||||
|
let dummyHead = ListNode(-1, head)
|
||||||
|
var fast: ListNode? = dummyHead
|
||||||
|
var slow: ListNode? = dummyHead
|
||||||
|
// fast 前移 n
|
||||||
|
for _ in 0 ..< n {
|
||||||
|
fast = fast?.next
|
||||||
|
}
|
||||||
|
while fast?.next != nil {
|
||||||
|
fast = fast?.next
|
||||||
|
slow = slow?.next
|
||||||
|
}
|
||||||
|
slow?.next = slow?.next?.next
|
||||||
|
return dummyHead.next
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
||||||
* B站视频:[代码随想录](https://space.bilibili.com/525438321)
|
* B站视频:[代码随想录](https://space.bilibili.com/525438321)
|
||||||
|
Reference in New Issue
Block a user