Principle: Set the speed pointer. The speed pointer and the slow pointer point to the first node of the linked list at the beginning, and then the fast pointer goes back to k units, so that the full pointer and the fast pointer go back at the same time, when the slow pointer value is null, the data domain of the node pointed by the fast pointer is required.
Algorithm:
# Include
Using namespace std; typedef int ElemType; typedef struct _ NODE _ // NODE declaration. The header Node data field stores the chain table length {ElemType data; struct _ NODE _ * next;} NODE, * pNode, * List; void search (List, int, int &); // search for the last k elements void printList (List); int main () {int size; cin> size; ElemType data; List list = (pNode) malloc (sizeof (Node); if (! List) {return-1;} list-> data = 0; list-> next = NULL; for (int I = 0; I <size; I ++) {cin> data; pNode pNew = (pNode) malloc (sizeof (Node); if (! PNew) {return-1;} pNew-> next = list-> next; pNew-> data = data; list-> next = pNew; list-> data ++ ;} cout <"print list:"; printList (list); int index, e; cin> index; search (list, index, e ); cout <"e =" <
List-> data) // judge return by the parameter; pNode p, q; // set the speed pointer p = q = list-> next; while (index --> 0) {/* if (! Q) {return;} */q = q-> next;} while (q) {p = p-> next; q = q-> next ;} e = p-> data;} void printList (List list) {if (! List) {return;} pNode p = list-> next; while (p) {cout <
Data <"; p = p-> next;} cout <
< pre>
Test:
<>