-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathKthNodeFromEnd.py
45 lines (43 loc) · 1011 Bytes
/
KthNodeFromEnd.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# -*- 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 head==None or k<=0:
return None
temp = head
n = 0
while temp:
n+=1
temp = temp.next
if n<k:
return None
p = head
for i in range(n-k):
p = p.next
return p
## Solution 2:
# -*- 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 head==None or k<=0:
return None
p = head
q = head
for i in range(k-1):
if q.next!=None:
q = q.next
else:
return None
while q.next!=None:
p = p.next
q = q.next
return p