List of the last K nodes in a list
- Number of participants: 1699 time limit: 1 seconds space limit: 32768K
- By scale: 21.37%
- Best record: 0 ms|8552k(from silent)
The title description enters a linked list, outputting the penultimate K node in the list.Title Link: http://www.nowcoder.com/practice/529d3ae5a407492994ad2a246518148a?rp=1&ru=/ta/coding-interviews &qru=/ta/coding-interviews/question-ranking
Elaboration, the interview when the topic has ambiguous or do not know the meaning of the time, must not be directly knocked, but to the interviewer to ask clear questions, this is very necessary, the interviewer will find out the details of your merits;
For the subject, pay attention to such points:
1, Understanding: The last node, in fact, is the bottom of the first node. (instead of the No. 0 node) that's k==0.
2, pay special attention to the case that the list is empty (ie: plisthead==null)
3, k> chain table length
Idea: Use two pointers to traverse the list; the difference between the two pointers is k-1 so that when the previous pointer reaches the end of the list, the subsequent nodes arrive at the penultimate position.
Xiao~k wrote a few lists, immediately after the next review.
#include <stdio.h> #include <iostream>using namespace std;struct listnode {int val;struct listnode *next; ListNode (int x): Val (x), Next (NULL) {}};class solution {public:listnode* findkthtotail (listnode* plisthead, unsigned i NT K) {ListNode *p,*q; if (!plisthead | |!k) return NULL; P=plisthead; Q=p; int cnt=0; while (p) {cnt++; p=p->next; if (cnt>k) {q=q->next; }} if (cnt<k) return NULL; else return q; } listnode* creatlist (ListNode *phead,int N) {if (n==0) return NULL; ListNode *p,*q; Phead=new ListNode (NULL); P=phead; cin>>p->val; int x; while (--n) {cin>>x; Q=new ListNode (x); p->next=q; p=q; } return phead; }};int Main () {int n,k; Solution so; ListNode *l; cin>>n; L=so. Creatlist (L,n); cin>>k; ListNode *ans=so. Findkthtotail (L,K); if (ans) printf ("%d\n", ans->val); return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
List of the last K nodes in the list (sword refers to an offer)