C language to achieve the reciprocal K-node _c language in the output list

Source: Internet
Author: User
Tags int size

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.

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.