Find a specific number in your link list

The length of the sequence: 7
The index: 0

The length of the sequence: 20
The index: 1

The corresponding codes:

//find a specific number in a link sequence
#include <iostream>
#include <iomanip>
#include <ctime>
#include <cstdlib>
using namespace std;
struct LNode{
    /* data */
    int value;
    LNode *next;
};
LNode *generate_Link(int n);
int find_value(LNode *head, int value);
int count = 0;
int main()
{
    // part_1 generate a link sequence; part_2 search a specific number in a link sequence
    srand((unsigned)time(NULL));
    cout << "The length of the sequence: ";
    int n;
    cin >> n;
    LNode *head = generate_Link(n);
    int value = rand() % 5;
    int index = find_value(head, value);
    cout << "The index: " << index << endl;
    return 0;
}
LNode *generate_Link(int n)
{
    if (n == 0) return NULL;
    LNode *head;
    head = new LNode;
    head->value = rand() % 10 + 1; //
    head->next = NULL;
    head -> next = generate_Link(n-1);
    return head;
}
int find_value(LNode *head, int value)
{
    if (head == NULL) return 0;
    count++;
    if (head -> value == value) return count;
    return find_value(head -> next, value);
}

猜你喜欢

转载自blog.csdn.net/weixin_38396940/article/details/121666894