链表中倒数第k个节点
Easy; 剑指 Offer 22; Linked List
Last updated
Easy; 剑指 Offer 22; Linked List
Last updated
给定一个链表: 1->2->3->4->5, 和 k = 2.
返回链表 4->5.# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def getKthFromEnd(self, head: ListNode, k: int) -> ListNode:
#
#1. method 1:
# loop through whole list and get the length of list
# then find the position of the kth node from tail
#
#2. method2:
# first reverse list
# then find the kth element from head
# then reverse the sublist to get the Kth From end
#
# Two methods have time O(n) and space O(1)
#base case:
#
if not head:
return None
cur = head
length = 0
while cur:
cur = cur.next
length +=1
if k > length:
return None
pos = length - k
cur_pos = 0
cur = head
while cur_pos!=pos:
cur = cur.next
cur_pos += 1
return cur
class Solution:
def getKthFromEnd(self, head: ListNode, k: int) -> ListNode:
# method 2
#
if not head:
return None
cur = new_head = self.reverse(head)
pos = 1
while pos != k:
cur = cur.next
pos += 1
cur.next = None
res = self.reverse(new_head)
return res
def reverse(self, node):
prev, cur = None, node
while cur:
next_node = cur.next
cur.next = prev
prev = cur
cur = next_node
return prev