#include using namespace std;

template struct node{ DataType data; node* next; };

template class linkList{ public: linkList(); ~linkList(); node* reverseFindK(int k); private: node* first; };

template linkList::linkList() { first = new node; first->next = NULL; node* rear = first; int n; cin >> n; for(int i=0; i<n; ++i){ DataType elem; cin >> elem; node* s = new node; s->data = elem; s->next = NULL; rear->next = s; rear = s; } }

template linkList::~linkList() { node* p; while(first != NULL){ p = first; first = first->next; delete p; } }

template node* linkList::reverseFindK(int k) { node* p = first->next; node* q = first->next; int count = 0; while(p != NULL){ if(count >= k) q = q->next; p = p->next; count++; } if(count < k) return NULL; else return q; }

int main() { linkList L; int k; cin >> k; node* p = L.reverseFindK(k); if(p == NULL) cout << 'Not Found' << endl; else cout << p->data << endl; L.~linkList(); return 0; }

C++单链表倒数第K个节点算法实现

原文地址: http://www.cveoy.top/t/topic/lGYO 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录