java:
又是重拳出击简单题
class Solution {
public ListNode getKthFromEnd(ListNode head, int k) {
int count = 0;
ListNode cur = head;
while(cur != null){
count ++;
cur = cur.next;
}
for( cur = head; k < count; count--){
cur = cur.next;
}
return cur;
}
}
双指针一下子~~~:
class Solution {
public ListNode getKthFromEnd(ListNode head, int k) {
ListNode fast = head;
ListNode slow = head;
while( fast != null && k>0 ){
fast = fast.next;
k --;
}
while( fast != null ){
fast = fast.next;
slow = slow.next;
}
return slow;
}
}
python3:
class Solution:
def getKthFromEnd(self, head: ListNode, k: int) -> ListNode:
cur = head
count = 0
while cur != None:
count += 1
cur = cur.next
cur = head
while k < count :
cur = cur.next
count -= 1
return cur
class Solution:
def getKthFromEnd(self, head: ListNode, k: int) -> ListNode:
fast = head
slow = head
while k > 0:
fast = fast.next
k -= 1
while fast != None:
fast = fast.next
slow = slow.next
return slow



