2487. Remove Nodes From Linked List

You are given the head of a linked list.

Remove every node which has a node with a greater value anywhere to the right side of it.

Return the head of the modified linked list.

Example 1:

Input: head = [5,2,13,3,8]
Output: [13,8]
Explanation: The nodes that should be removed are 5, 2 and 3.
- Node 13 is to the right of node 5.
- Node 13 is to the right of node 2.
- Node 8 is to the right of node 3.

Example 2:

Input: head = [1,1,1,1]
Output: [1,1,1,1]
Explanation: Every node has value 1, so no nodes are removed.
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* removeNodes(ListNode* head) {
        stack<ListNode *> st;
        while(head->next != nullptr){
            st.push(head);
            head = head->next;
        }
        while(!st.empty()){
            if(st.top()->val >=head->val||head==nullptr){
                st.top()->next = head;
                head = st.top();
            }
            st.pop();
        }
        return head;

    }
};

相关推荐

  1. P2437 蜜蜂路线

    2024-01-07 07:04:05       61 阅读
  2. 2407-mysql笔记

    2024-01-07 07:04:05       20 阅读
  3. LeetCode——2487. 从链表中移除节点

    2024-01-07 07:04:05       50 阅读
  4. Leetcode 287. 寻找重复数

    2024-01-07 07:04:05       44 阅读
  5. leetcode——287 寻找重复数

    2024-01-07 07:04:05       44 阅读
  6. LeetCode 287 寻找重复数字

    2024-01-07 07:04:05       34 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-07 07:04:05       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-07 07:04:05       101 阅读
  3. 在Django里面运行非项目文件

    2024-01-07 07:04:05       82 阅读
  4. Python语言-面向对象

    2024-01-07 07:04:05       91 阅读

热门阅读

  1. uView IndexList 索引列表

    2024-01-07 07:04:05       60 阅读
  2. Kotlin: Jetpack — ViewModel简单应用

    2024-01-07 07:04:05       55 阅读
  3. Nacos vs. Eureka:微服务注册中心的对比

    2024-01-07 07:04:05       63 阅读
  4. 【复现】DiffTalk

    2024-01-07 07:04:05       60 阅读
  5. WPF 怎么判断MediaElement视频播放完成

    2024-01-07 07:04:05       55 阅读
  6. 构建SaaS数据分析和反馈体系的最佳实践

    2024-01-07 07:04:05       83 阅读
  7. sd-webui-EasyPhoto win 安装笔记

    2024-01-07 07:04:05       61 阅读
  8. IDEA TODO

    IDEA TODO

    2024-01-07 07:04:05      53 阅读
  9. kafka生产者设置ack、消费者设置自动提交实例

    2024-01-07 07:04:05       64 阅读