題目描述
輸入一個鏈表,輸出該鏈表中倒數第k個結點,解題思路:
這個題目也延續了劍指offer題目當中資訊不給全的傳統,其中代碼當中的第一個引數head表示鏈表的表頭Node,k表示的是一個數字,我們只需要遍歷所有Node,將這些Node放進一個堆疊當中即可(用串列來代替堆疊),然后找到堆疊當中的倒數第K個節點輸出即可,代碼如下:
# -*- 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 #這個k表示的是倒數第k,而不是正數第k #k如果比鏈表的長度還有大的話就回傳None if head==None or head.next==None: return None ls=[] i=0 while head: ls.append(head) head=head.next length=len(ls) zhengshu=length-k+1 if k>len(ls) or k<1:#這里還需要考慮k<1的情況,實在是太坑人了 return None else: return ls[zhengshu-1]
得解也!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/3872.html
標籤:其他
