diff --git "a/problems/0019.\345\210\240\351\231\244\351\223\276\350\241\250\347\232\204\345\200\222\346\225\260\347\254\254N\344\270\252\350\212\202\347\202\271.md" "b/problems/0019.\345\210\240\351\231\244\351\223\276\350\241\250\347\232\204\345\200\222\346\225\260\347\254\254N\344\270\252\350\212\202\347\202\271.md" index 3e1a682c45..4d3e57db35 100644 --- "a/problems/0019.\345\210\240\351\231\244\351\223\276\350\241\250\347\232\204\345\200\222\346\225\260\347\254\254N\344\270\252\350\212\202\347\202\271.md" +++ "b/problems/0019.\345\210\240\351\231\244\351\223\276\350\241\250\347\232\204\345\200\222\346\225\260\347\254\254N\344\270\252\350\212\202\347\202\271.md" @@ -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) * B站视频:[代码随想录](https://space.bilibili.com/525438321) diff --git "a/problems/0024.\344\270\244\344\270\244\344\272\244\346\215\242\351\223\276\350\241\250\344\270\255\347\232\204\350\212\202\347\202\271.md" "b/problems/0024.\344\270\244\344\270\244\344\272\244\346\215\242\351\223\276\350\241\250\344\270\255\347\232\204\350\212\202\347\202\271.md" index 91e566ddd6..55a6bb5077 100644 --- "a/problems/0024.\344\270\244\344\270\244\344\272\244\346\215\242\351\223\276\350\241\250\344\270\255\347\232\204\350\212\202\347\202\271.md" +++ "b/problems/0024.\344\270\244\344\270\244\344\272\244\346\215\242\351\223\276\350\241\250\344\270\255\347\232\204\350\212\202\347\202\271.md" @@ -248,6 +248,27 @@ fun swapPairs(head: ListNode?): ListNode? { } ``` +Swift: +```swift +func swapPairs(_ head: ListNode?) -> ListNode? { + if head == nil || head?.next == nil { + return head + } + let dummyHead: ListNode = ListNode(-1, head) + var current: ListNode? = dummyHead + while current?.next != nil && current?.next?.next != nil { + let temp1 = current?.next + let temp2 = current?.next?.next?.next + + current?.next = current?.next?.next + current?.next?.next = temp1 + current?.next?.next?.next = temp2 + + current = current?.next?.next + } + return dummyHead.next +} +``` -----------------------