在 C++ 中查找单链表中最小的和最大的元素
在这个问题中,我们给定一个单链表。我们的任务是找到单链表中最小的和最大的元素。
我们举个例子来理解这个问题,
输入
linked List : 5 -> 2 -> 7 -> 3 ->9 -> 1 -> 4
输出
Smallest element = 1 Largest element = 9
解决方案方法
解决这个问题的一个简单方法是逐个遍历链表节点。在此之前,我们将 maxElement 和 minElement 初始化为第一个元素的值,即 head -> data。然后,我们将逐个元素遍历链表。然后将当前节点的值与 maxElement 进行比较,并将较大的值存储在 maxElement 变量中。对 minElement 执行相同的操作以存储较小的值。当遍历完成时,打印两个值。
演示我们解决方案工作原理的程序,
示例
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node* next;
};
void printLargestSmallestLinkedList(struct Node* head) {
int maxElement = INT_MIN;
int minElement = INT_MAX;
while (head != NULL) {
if (minElement > head->data)
minElement = head->data;
if (maxElement < head->data)
maxElement = head->data;
head = head->next;
}
cout<<"Smallest element in the linked list is : "<<minElement<<endl;
cout<<"Largest element in the linked list is : "<<maxElement<<endl;
}
void push(struct Node** head, int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = (*head);
(*head) = newNode;
}
int main() {
struct Node* head = NULL;
push(&head, 5);
push(&head, 2);
push(&head, 7);
push(&head, 3);
push(&head, 9);
push(&head, 1);
push(&head, 4);
printLargestSmallestLinkedList(head);
return 0;
}输出
Smallest element in the linked list is : 1 Largest element in the linked list is : 9
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 程序设计
C++
C#
MongoDB
MySQL
JavaScript
PHP