This article shows the C + + implementation of the output list of the reciprocal K-node method, share for everyone for reference purposes.
Running the example described in this article can be achieved by inputting a one-way linked list and outputting the reciprocal k nodes in the list.
The implementation methods are as follows:
/* Copyright (c) alexingcool.
All Rights Reserved.
* * #include <iostream> using namespace std;
int array[] = {5, 7, 6, 9, 11, 10, 8};
const int size = sizeof array/sizeof *array;
struct Node {node (int i = 0, Node *n = NULL): item (i), next (n) {} int item;
Node *next;
};
node* construct (int (&array) [size]) {Node dummy;
Node *head = &dummy;
for (int i = 0; i < size; i++) {Node *temp = new Node (Array[i]);
Head->next = temp;
Head = temp;
return dummy.next;
} void Print (Node *head) {while (head) {cout << head->item << "";
Head = head->next;
} node* Findknode (node *head, int k) {node *pknode = head;
if (head = = null) {cout << "link is null" << Endl;
return NULL;
while (k--) {if (head = = NULL) {cout << "K is bigger than" the length of the "link" << Endl;
return NULL;
Head = head->next;
While [head] {head = head->next;
Pknode = pknode->next; } returnPknode;
} void Main () {Node *head = construct (array);
cout << "source Link:";
Print (head);
cout << Endl;
Node *knode = Findknode (head, 5);
if (Knode!= NULL) cout << "The Knode is:" << knode->item << Endl;}
Test cases are as follows:
1. NULL Link
head = NULL;
2. Normal Link, with normal K
K <= Len (head);
3. Normal Link, with invalid K
K > Len (head)
I hope this article is helpful to the learning of C program algorithm design.