# -*- 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 Node=[] while head!=None: Node.append(head) head=head.next if k>len(Node) or k<1: return return Node[-k]
/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } };*/ class Solution { public: ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) { if(pListHead == NULL || k == 0) return NULL; ListNode* p=pListHead;//两个指针p、q分别从链表头往尾部跑 ListNode* q=pListHead; int n=k-1; while(n--){ if(p->next!=NULL) p=p->next; else return NULL;//p指针先跑,当p跑了k-1个节点时,q再跑;当p跑到末尾时,q为所求 } while(p->next!=NULL){//即p和q之间相差k-1个节点 p=p->next; q=q->next; } return q; } };