Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 输入一个链表,输出该链表中倒数第k个结点。
- * solution1: Two pointers
- ```python3
- # -*- coding:utf-8 -*-
- # class ListNode:
- # def __init__(self, x):
- # self.val = x
- # self.next = None
- class Solution:
- def FindKthToTail(self, head, k):
- # write code here
- if not head or k <=0:
- return None
- p2 = head
- p1 = head
- while k > 1:
- if p2.next:
- p2 = p2.next
- k -= 1
- else:
- return None
- while p2.next:
- p1 = p1.next
- p2 = p2.next
- return p1
- ```
- * solution2: Brute Force
- ```python3
- # -*- coding:utf-8 -*-
- # class ListNode:
- # def __init__(self, x):
- # self.val = x
- # self.next = None
- class Solution:
- def FindKthToTail(self, head, k):
- # write code here
- res = []
- while head:
- res.append(head)
- head = head.next
- if len(res) < k or k <1:
- return
- return res[-k]
- ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement