程序在C ++中查找双链表的大小
在本教程中,我们将讨论一个程序来查找双链表的大小。
为此,我们将提供一个双向链接列表。我们的任务是找到链表的大小,即链表中元素的数量。
示例
#include <bits/stdc++.h>
using namespace std;
//structure of linked list node
struct Node {
int data;
struct Node *next;
struct Node *prev;
};
void push(struct Node** head_ref, int new_data) {
struct Node* new_node = new Node;
new_node->data = new_data;
new_node->next = (*head_ref);
new_node->prev = NULL;
if ((*head_ref) != NULL)
(*head_ref)->prev = new_node ;
(*head_ref) = new_node;
}
//returning size of linked list
int findSize(struct Node *node) {
int res = 0;
while (node != NULL){
res++;
node = node->next;
}
return res;
}
int main() {
struct Node* head = NULL;
push(&head, 4);
push(&head, 3);
push(&head, 2);
push(&head, 1);
cout << findSize(head);
return 0;
}输出结果
4