C++程序:查找双向链表的大小
在这个问题中,我们给定一个双向链表。我们的任务是创建一个C++程序来查找双向链表的大小。
双向链表是一种特殊的链表,与单向链表相比,它可以更容易地向前和向后导航。以下是一些理解双向链表概念的重要术语。
链接 - 链表的每个链接都可以存储一个称为元素的数据。
下一个 - 链表的每个链接都包含一个指向下一个链接的链接,称为Next。
前一个 - 链表的每个链接都包含一个指向前一个链接的链接,称为Prev。
链表 - 链表包含指向第一个链接(称为First)和最后一个链接(称为Last)的连接链接。
双向链表的表示 -

问题描述 - 我们将得到上述类型的双向链表。我们将找到它的长度(大小)。
让我们举个例子来理解这个问题,
输入
the above linked list A <-> B <-> C.
输出
3
解决方案方法
要查找双向链表的大小,我们需要遍历双向链表并使用长度变量跟踪长度。
算法
初始化 - length = 0,*temp = head
- 步骤1 - 遍历列表,即执行直到temp != NULL。
- 步骤1.1 - 增加长度,length++
- 步骤1.2 - 更新指针,temp = temp -> next。
- 步骤2 - 打印长度。
程序说明我们解决方案的工作原理
示例
#include <iostream>
using namespace std;
struct doublyLL {
char val;
struct doublyLL *next;
struct doublyLL *prev;
};
void insertNode(struct doublyLL** head_ref, int value){
struct doublyLL* new_node = new doublyLL;
new_node->val = value;
new_node->next = (*head_ref);
new_node->prev = NULL;
if ((*head_ref) != NULL)
(*head_ref)->prev = new_node ;
(*head_ref) = new_node;
}
int calcDLLSize(struct doublyLL *temp) {
int length = 0;
while (temp != NULL){
temp = temp->next;
length++;
}
return length;
}
int main(){
struct doublyLL* head = NULL;
insertNode(&head, 'A');
insertNode(&head, 'H');
insertNode(&head, 'E');
insertNode(&head, 'K');
insertNode(&head, 'M');
insertNode(&head, 'S');
cout<<"The size of Doubly Linked List is "<<calcDLLSize(head);
return 0;
}输出
The size of Doubly Linked List is 6
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP