c_cpp 搜索链接列表中的元素(迭代和递归)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 搜索链接列表中的元素(迭代和递归)相关的知识,希望对你有一定的参考价值。

// https://www.geeksforgeeks.org/search-an-element-in-a-linked-list-iterative-and-recursive/
#include <iostream>
#include <list>
using namespace std;

struct linked_list {
    int data;
    struct linked_list* next;
};
typedef struct linked_list node;
node* head;

void insert(int n) {
    node* list = (node*)malloc(sizeof(node*));
    list->data = n;
    list->next = head;
    head = list;
}

int search (node* list, int x) {
    if (list == NULL)
        return 0;
    if (list->data==x)
        return 1;
    return search(list->next,x);
}

int main () {
    int n;
    head = NULL;
    while (true) {
        cout<< "Enter the element, enter -9 to stop: ";
        cin>>n;
        if (n==-9)
            break;
        else
            insert(n);
    }
    cout<< "Enter the search element: ";
    cin>>n;
    if (search(head, n)==1)
        cout<< "Yes!";
    else
        cout<< "No!";


}
// https://www.geeksforgeeks.org/search-an-element-in-a-linked-list-iterative-and-recursive/
#include <iostream>
#include <list>
using namespace std;

struct linked_list {
    int data;
    struct linked_list* next;
};
typedef struct linked_list node;
node* head;

void insert(int n) {
    node* list = (node*)malloc(sizeof(node*));
    list->data = n;
    list->next = head;
    head = list;
}

int main () {
    int n;
    head = NULL;
    while (true) {
        cout<< "Enter the element, enter -9 to stop: ";
        cin>>n;
        if (n==-9)
            break;
        else
            insert(n);
    }
    cout<< "Enter the search element: ";
    cin>>n;

    while (head != NULL) {
        if (head->data == n){
            cout<< "Yes!";
            exit(0);
        }
        head = head->next;
    }
    cout<< "No!";
}

以上是关于c_cpp 搜索链接列表中的元素(迭代和递归)的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp 合并两个排序列表,递归和迭代

Medium | LeetCode 341. 扁平化嵌套列表迭代器 | 递归 | 栈

Python - 如何递归搜索作为列表元素的文本中的变量子字符串

c_cpp 203.删除链接列表元素

c_cpp 反向链表,迭代,递归

c_cpp 203.删除链接列表元素 - easy - 2018.8.1