您好,欢迎访问一九零五行业门户网

C++程序:在链表中找到第二小的元素

数据元素的有序集合,每个数据元素都有一个到它的下一个元素(有时是它的前一个元素)的链接,假设有一个链表,那么我们需要找到第二小的元素。以下是以下场景。
让我们假设一些简单的输入和输出场景
假设这个场景,我们有一个链表,其中包含的元素是“8->4->6->2->9,”。然后在迭代整个链表之后,第二小的元素是 8。
input = 8->4->6->2->9output = 8
链表的编程实现方式
node* head = new node(8);head->next = new node(4);head->next->next = new node(6);head->next->next->next = new node(2);head->next->next->next->next = new node(9);result = solve(head);
考虑另一种情况,链表中的每个元素都具有相同的值。迭代完所有元素后,链表中将找不到第二小的元素。由于链表中的元素每个元素都包含相同的值。
input = 1->1->1->1->1->1output = there is no second smallest element in linked list
算法以下是执行任务时应遵循的步骤
分配两个变量(s1,s2)
s1 将保存链表中最小的元素
s2 将保存链表中第二小的元素。
每次迭代,最小的元素都会移动到s1,遇到它就移动到s2
当最小(s1)小于新的较小值时,新的较小将成为最小(s1)。
新的较小的将变得更小(s1),较小的(s1)将移动到第二个较小的(s2)。
在每次可能的遍历之后,最终输出中的第二小的元素将作为输出。
示例在c++实现中,我们可以保留2个变量。 1为最小,other为次小,然后遍历链表,每次遇到更小的元素时,将最小的变量更新到次小,新的较小的就变成最小的。因此,每当一个元素小于最小的元素时,第二小的元素就会变成最小的,最小的元素就会成为新元素。如果不是,我们比较第二小的元素并确定当前元素是否小于第二小的元素,然后进行相应的更新。
#include <iostream>using namespace std;class node { public: int val; node *next; node(int val) { this->val = val; next = null; }};int solve(node* root) { int s1=root->val, s2=root->val; while(root) { if(root->val <= s1) { s2 = s1; s1 = root->val; } else if(root->val < s2) { s2 = root->val; } root = root->next; } return s2;}int main() { node* head = new node(5); head->next = new node(8); head->next->next = new node(9); head->next->next->next = new node(2); head->next->next->next->next = new node(4); cout << second smallest element in the linked list is : << solve(head); return 0;}
输出second smallest element in the linked list is: 4
结论遍历链表一次,时间复杂度为o(n)。如果您觉得上述信息有用,那么请务必访问我们的官方网站以了解更多有关编程的相关主题。
以上就是c++程序:在链表中找到第二小的元素的详细内容。
其它类似信息

推荐信息