问题描述
给出一个单向链表。链表中的节点分别编号为:node_1, node_2, node_3, ... 。
每个节点都可能有下一个更大值(next larger value):对于 node_i,如果其 next_larger(node_i) 是 node_j.val,那么就有 j > i 且 node_j.val > node_i.val,而 j 是可能的选项中最小的那个。如果不存在这样的 j,那么下一个更大值为 0 。
返回整数答案数组(代码中是vector) answer,其中 answer[i] = next_larger(node_{i+1}) 。
注意:在下面的示例中,诸如 [2,1,5] 这样的输入(不是输出)是链表的序列化表示,其第一个节点的值为 2,第二个节点值为 1,第三个节点值为 5 。
示例 1:
输入:[2,1,5]
输出:[5,5,0]
示例 2:
输入:[2,7,4,3,5]
输出:[7,0,5,5,0]
示例 3:
输入:[1,7,5,1,9,2,5,1]
输出:[7,9,9,9,0,5,0,0]
说明:
对于链表中的每个节点,1 <= node.val <= 10^9
给定列表的长度在 [0, 10000] 范围内
可使用以下代码,完成其中的nextLargerNodes函数,其中形参head指向无头结点单链表,返回如上描述的数组(vector)。
#include<iostream>
#include<vector>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode() : val(0), next(NULL) {}
ListNode(int x) : val(x), next(NULL) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution {
public:
vector<int> nextLargerNodes(ListNode* head) {
//填充本函数完成功能
}
};
ListNode *createByTail()
{
ListNode *head;
ListNode *p1,*p2;
int n=0,num;
int len;
cin>>len;
head=NULL;
while(n<len && cin>>num)
{
p1=new ListNode(num);
n=n+1;
if(n==1)
head=p1;
else
p2->next=p1;
p2=p1;
}
return head;
}
int main()
{
ListNode* head = createByTail();
vector<int> res=Solution().nextLargerNodes(head);
for(int i=0; i<res.size(); i++)
{
if (i>0) cout<<" ";
cout<<res[i];
}
cout<<endl;
return 0;
}
输入说明
首先输入链表长度len,然后输入len个整数,以空格分隔。
输出说明
输出格式见范例
输入范例
8
1 7 5 1 9 2 5 1
输出范例
7 9 9 9 0 5 0 0
实现思路
每次都从头结点开始遍历,寻找比该结点大的值,一轮寻找结束后使head = head->next,直至head==NULL。
实现代码
#include<iostream>
#include<vector>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode() : val(0), next(NULL) {}
ListNode(int x) : val(x), next(NULL) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution {
public:
vector<int> nextLargerNodes(ListNode* head) {
//填充本函数完成功能
vector<int> res;
ListNode *p = head;
while(head){
p = head;//每次都从头结点开始遍历
int tag = 0;//tag为0则说明没有找到一个比当前结点大的
int maxnum = p->val;
p = p->next;//从p的下一个结点开始寻找比p大的结点
while(p){
if(p->val > maxnum){
res.push_back(p->val);
tag = 1;//找到
break;
}
p = p->next;
}
if(tag==0){
res.push_back(0);//若未找到则该点的值为0
}
head = head->next;//为下一个结点寻找
}
return res;
}
};
ListNode *createByTail()
{
ListNode *head;
ListNode *p1,*p2;
int n=0,num;
int len;
cin>>len;
head=NULL;
while(n<len && cin>>num)
{
p1=new ListNode(num);
n=n+1;
if(n==1)
head=p1;
else
p2->next=p1;
p2=p1;
}
return head;
}
int main()
{
ListNode* head = createByTail();
vector<int> res=Solution().nextLargerNodes(head);
for(int i=0; i<res.size(); i++)
{
if (i>0) cout<<" ";
cout<<res[i];
}
cout<<endl;
return 0;
}