C + + single-linked list to find the penultimate K node (time complexity O (n) Oh, with 2 pointers to the K-node)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.