java思路:第一个指针从链表的头指针开始遍历向前走k-1步,第二个指针保持不变;从第k步开始,第二个指针开始从链表的头指针开始遍历。由于两个指针的距离保持在k-1,因此在第二个指针走到链表尾部的时候,第一个指针在倒数第k个位置。
java代码:
/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Solution { public ListNode FindKthToTail(ListNode head,int k) { ListNode firstnode =head; ListNode secondnode=head; if(listnode==null){ return null; } if(k<=0){ return null; } for(int i=0;i<k-1;i++){ firstnode=firstnode.next; } if(firstnode==null){ return null; } while(firstnode.next!=null){ firstnode=firstnode.next; secondnode=secondnode.next; } return secondnode; } }
python思路:用列表存储链表的内容,然后访问列表倒数第k个位置的元素即可。
代码:
class Solution: def FindKthToTail(self, head, k): tempList=[] firstNode=head while firstNode!=None: tempList.append(firstNode) firstNode=firstNode.next if k<=0: return None if k>len(tempList): return None return tempList[-k]