Enter a one-way list to output the last K nodes in the linked list. The bottom No. 0 node of the list is the tail pointer of the linked list. My idea is 2 pointers to the back, you think Ah, if it is a pointer, it must traverse 2 times, the first traversal total number of nodes, the second time to traverse the final result//Such a practice is obviously not good enough, time complexity into 2n, but if we use 2 pointers, the distance between them K nodes, When one node arrives at null//(tail), the other node is the node we requested can return the result. #include <iostream>using namespace Std;template<typename t> struct listnode{T m_nkey;//data field listnode* m_pnext;//pointer field ListNode (): M_nkey (t ()), M_pnext (NULL) {}listnode (t value): m_ Nkey (value), M_pnext (NULL) {}};template<typename T>class list{public:list () {head = new listnode<t> ();} void Insert (T value) {listnode<t> *s = new listnode<t> (value); s->m_pnext = head->m_pnext;//head Plug-in node. head- >m_pnext = s;} listnode<t>* find (int k)//Find the target node. {listnode<t> *p = head; listnode<t> *q = head;for (int i=0;i<k;i++)//Let the P pointer go first (Let the bullet fly for a while). {p=p->m_pnext;if (p==null) return NULL;} while (p!=null)//q,p at the same time, know that p goes to the end, and then return q is the result. {Q=q->m_pnext;p=p->m_pnext;} return q;} T Getvalue (listnode<t> *t)//based on the node to get the value, test. {return t->m_nkey;} Private:listnode<t> *head;};int Main () {list<int> list;int item;while (cin>>item,item!=-1) {List. Insert (Item);} Cout<<list. Getvalue (list. Find (4)) <<endl;return 0;}
C + + single-linked list to find the penultimate K node (time complexity O (n) Oh, with 2 pointers to the K-node)