/** 链表节点 */ classListNode { var val: Int var next: ListNode? init(_val: Int) { self.val = val self.next =nil } } /** LeetCode-剑指offer22.链表中倒数k个节点 */ funcgetKthFromEnd(_head: ListNode?, _k: Int) -> ListNode? { var fast = head var slow = head // 快指针先行k步 for_in1... k { if fast !==nil { fast = fast?.next } else { // 达不到k步说明链表过短,没有倒数k returnnil } } // 快慢指针同步,快指针先到底,慢指针指向倒数第k个 while fast !==nil { fast = fast?.next slow = slow?.next } return slow }
/** 链表节点 */ classListNode { var val: Int var next: ListNode? init(_val: Int) { self.val = val self.next =nil } } /** 遍历法 */ funcgetKthFromEnd2(_head: ListNode?, _k: Int) -> ListNode? { var n =0 var cur = head while cur !==nil { cur = cur?.next n +=1 } if n < k { returnnil } cur = head for_in0..< n - k { cur = cur?.next } return cur }