c_cpp 查找链接列表的长度(迭代和递归)

Posted

tags:

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

// // https://www.geeksforgeeks.org/find-length-of-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 length (node* list) {
    if (list == NULL)
        return 0;
    return 1+length(list->next);
}

int main () {
    int n;
    while(true) {
        cout<< "Enter the element, enter -9 to stop: ";
        cin>>n;
        if (n == -9)
            break;
        else
            insert(n);
    }
    n = length(head);
    cout<< "Length is "<< n;
}
// https://www.geeksforgeeks.org/find-length-of-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);
    }
    n = 0;
    node* list = head;
    while (list != NULL) {
        n++;
        list = list->next;
    }
    cout<< "Length of list is " << n;
}

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

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

c_cpp 反向链表,迭代,递归

使用承诺和递归迭代文件目录

散列表的平均查找长度怎么计算?

递归二分查找

c_cpp 在链表中查找循环的长度