在 C++ 中找到双链表中的最大节点
在此问题中,我们获得了一个双链表 LL。我们的任务是在双链表中找到最大的节点。
让我们举个例子来理解这个问题,
Input : linked-list = 5 -> 2 -> 9 -> 8 -> 1 -> 3 Output : 9
解决方案方法
解决此问题的一种简单方法是遍历链表,如果 max 的数据值大于 maxVal 的数据。遍历链表后,我们将返回 macVal 节点的数据。
示例
演示我们解决方案工作原理的程序
#include <iostream>
using namespace std;
struct Node{
int data;
struct Node* next;
struct Node* prev;
};
void push(struct Node** head_ref, int new_data){
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->prev = NULL;
new_node->next = (*head_ref);
if ((*head_ref) != NULL)
(*head_ref)->prev = new_node;
(*head_ref) = new_node;
}
int findLargestNodeInDLL(struct Node** head_ref){
struct Node *maxVal, *curr;
maxVal = curr = *head_ref;
while (curr != NULL){
if (curr->data > maxVal->data)
maxVal = curr;
curr = curr->next;
}
return maxVal->data;
}
int main(){
struct Node* head = NULL;
push(&head, 5);
push(&head, 2);
push(&head, 9);
push(&head, 1);
push(&head, 3);
cout<<"The largest node in doubly linked-list is "<<findLargestNodeInDLL(&head);
return 0;
}输出
The largest node in doubly linked-list is 9
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP