The title description enters a linked list, outputting the penultimate K node in the list. Train of Thought: Method 1: Set 2 pointer p,q. P moves the K-time first, and then the PQ moves back, p to the end of the list, Q points to the last K-node. Attention://need to consider k=0, and the case of list is emptyMethod 2: Use the stack, first all stack, pop k times, get the countdown k node AC code:
1 /*2 struct ListNode {3 int val;4 struct ListNode *next;5 listnode (int x):6 val (x), Next (NULL) {7 }8 };*/9 classSolution {Ten Public: Onelistnode* Findkthtotail (listnode* plisthead, unsignedintk) { A if(k==0|| Plisthead==null)//need to consider k=0, and the case that list is empty - returnNULL; - theListNode *p,*Q; -p=Plisthead; -q=Plisthead; - + for(intI=1; i<k;i++)//note the boundary value, starting from 1 - { + if(p->next!=NULL) AP=p->Next; at Else - returnNULL; - } - - while(p->next!=NULL) - { inP=p->Next; -Q=q->Next; to } + - returnQ; the * } $};
Sword refers to the reciprocal K-node in the Offer list.