给定一个链表,任务是为链表的每个节点找到下一个更大的元素。
注意:对于没有下一个更大元素的节点,在结果中存储 -1。
例子:
Input: linked list = [2, 1, 5]
Output: [5, 5, -1]
Input: linked list = [2, 7, 4, 3, 5]
Output: [7, -1, 5, 5, -1]
方法:
解决上述问题的主要思想是使用堆栈数据结构。
- 遍历链表并将链表元素的值和位置插入堆栈。
- 用 -1 为每个节点初始化结果向量。
- 当当前节点的值大于前一个节点时更新前一个节点的值,更新后从堆栈中弹出该值。
下面是上述方法的实现:
C++
// C++ Program to find the
// Next Greater Element for
// a Linked List
#include
using namespace std;
// Linked List Node
struct Node {
int val;
struct Node* next;
};
// Function to print
// next greater element
vector nextLargerNodes(
struct Node* head)
{
int cur_pos = 0;
stack > arr;
vector res;
// Iterate for all
// element in linked list
while (head) {
// Initialize every
// position with 0
res.push_back(-1);
// Check if current value is
// greater then update previous
while (
!arr.empty()
&& arr.top().second
< head->val) {
res[arr.top().first]
= head->val;
arr.pop();
}
arr.push(make_pair(
cur_pos,
head->val));
cur_pos++;
// Increment the head pointer
head = head->next;
}
// Return the final result
return res;
}
// Utility function to
// create a new node
Node* newNode(int val)
{
struct Node* temp = new Node;
temp->val = val;
temp->next = NULL;
return temp;
}
// Driver Program
int main()
{
struct Node* head = newNode(2);
head->next = newNode(7);
head->next->next = newNode(4);
head->next->next->next = newNode(3);
head->next->next->next->next = newNode(5);
vector ans;
ans = nextLargerNodes(head);
for (int i = 0; i < ans.size(); i++) {
cout << ans[i] << ", ";
}
}
Java
// Java Program to find the
// Next Greater Element for
// a Linked List
import java.util.*;
class GFG{
// Linked List Node
static class Node
{
int val;
Node next;
};
static class pair
{
int first, second;
public pair(int first,
int second)
{
this.first = first;
this.second = second;
}
} ;
// Function to print
// next greater element
static Vector
nextLargerNodes(Node head)
{
int cur_pos = 0;
Stack arr = new Stack<>();
Vector res = new Vector<>();
// Iterate for all
// element in linked list
while (head != null)
{
// Initialize every
// position with 0
res.add(-1);
// Check if current value is
// greater then update previous
while (!arr.isEmpty() &&
arr.peek().second <
head.val)
{
res.set(arr.peek().first,
head.val);
arr.pop();
}
arr.add(new pair(cur_pos,
head.val));
cur_pos++;
// Increment the head
// pointer
head = head.next;
}
// Return the final result
return res;
}
// Utility function to
// create a new node
static Node newNode(int val)
{
Node temp = new Node();
temp.val = val;
temp.next = null;
return temp;
}
// Driver code
public static void main(String[] args)
{
Node head = newNode(2);
head.next = newNode(7);
head.next.next = newNode(4);
head.next.next.next = newNode(3);
head.next.next.next.next = newNode(5);
Vector ans = new Vector<>();
ans = nextLargerNodes(head);
for (int i = 0; i < ans.size(); i++)
{
System.out.print(ans.elementAt(i) + ", ");
}
}
}
// This code is contributed by Princi Singh
Python3
# Python3 program to find the
# Next Greater Element for
# a Linked List
# Linked List Node
class newNode:
def __init__(self, val):
self.val = val
self.next = None
# Function to print
# next greater element
def nextLargerNodes(head):
cur_pos = 0
arr = []
res = []
# Iterate for all
# element in linked list
while (head):
# Initialize every
# position with 0
res.append(-1)
# Check if current value is
# greater then update previous
while (len(arr) > 0 and
arr[len(arr) - 1][1] < head.val):
res[arr[len(arr) - 1][0]] = head.val
arr.remove(arr[len(arr) - 1])
arr.append([cur_pos, head.val])
cur_pos += 1
# Increment the head pointer
head = head.next
# Return the final result
return res
# Driver code
if __name__ == '__main__':
head = newNode(2)
head.next = newNode(7)
head.next.next = newNode(4)
head.next.next.next = newNode(3)
head.next.next.next.next = newNode(5)
ans = nextLargerNodes(head)
for i in range(len(ans)):
print(ans[i], end = ", ")
# This code is contributed by SURENDRA_GANGWAR
C#
// C# Program to find the
// Next Greater Element for
// a Linked List
using System;
using System.Collections.Generic;
class GFG{
// Linked List Node
class Node
{
public int val;
public Node next;
};
class pair
{
public int first, second;
public pair(int first,
int second)
{
this.first = first;
this.second = second;
}
} ;
// Function to print
// next greater element
static List
nextLargerNodes(Node head)
{
int cur_pos = 0;
Stack arr = new Stack();
List res = new List();
// Iterate for all
// element in linked list
while (head != null)
{
// Initialize every
// position with 0
res.Add(-1);
// Check if current value is
// greater then update previous
while (arr.Count !=0 &&
arr.Peek().second <
head.val)
{
res[arr.Peek().first] =
head.val;
arr.Pop();
}
arr.Push(new pair(cur_pos,
head.val));
cur_pos++;
// Increment the head
// pointer
head = head.next;
}
// Return the readonly result
return res;
}
// Utility function to
// create a new node
static Node newNode(int val)
{
Node temp = new Node();
temp.val = val;
temp.next = null;
return temp;
}
// Driver code
public static void Main(String[] args)
{
Node head = newNode(2);
head.next = newNode(7);
head.next.next = newNode(4);
head.next.next.next = newNode(3);
head.next.next.next.next = newNode(5);
List ans = new List();
ans = nextLargerNodes(head);
for (int i = 0; i < ans.Count; i++)
{
Console.Write(ans[i] + ", ");
}
}
}
// This code is contributed by shikhasingrajput
输出:
7, -1, 5, 5, -1,
时间复杂度: O(N)
辅助空间复杂度: O(N)
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live