SHARE
TWEET

Untitled

a guest Apr 26th, 2019 53 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. 输入一个链表,输出该链表中倒数第k个结点。
  2.  
  3. * solution1: Two pointers
  4. ```python3
  5. # -*- coding:utf-8 -*-
  6. # class ListNode:
  7. #     def __init__(self, x):
  8. #         self.val = x
  9. #         self.next = None
  10.  
  11. class Solution:
  12.     def FindKthToTail(self, head, k):
  13.         # write code here
  14.         if not head or k <=0:
  15.             return None
  16.         p2 = head
  17.         p1 = head
  18.         while k > 1:
  19.             if p2.next:
  20.                 p2 = p2.next
  21.                 k -= 1
  22.             else:
  23.                 return None
  24.         while p2.next:
  25.             p1 = p1.next
  26.             p2 = p2.next
  27.         return p1
  28.        
  29. ```
  30.  
  31. * solution2: Brute Force
  32. ```python3
  33. # -*- coding:utf-8 -*-
  34. # class ListNode:
  35. #     def __init__(self, x):
  36. #         self.val = x
  37. #         self.next = None
  38.  
  39. class Solution:
  40.     def FindKthToTail(self, head, k):
  41.         # write code here
  42.         res = []
  43.         while head:
  44.             res.append(head)
  45.             head = head.next
  46.         if len(res) < k or k <1:
  47.             return
  48.         return res[-k]
  49. ```
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top