做电商网站搭建就业岗位,汽车之家手机版网页,十大黄金软件app免费,wordpress主机服务器销售源码2024-1-3 文章目录 [2487. 从链表中移除节点](https://leetcode.cn/problems/remove-nodes-from-linked-list/)方法一#xff1a;调用栈方法二#xff1a;递归方法三#xff1a;翻转链表 2487. 从链表中移除节点 方法一#xff1a;调用栈
1.将所有节点按顺序压入栈中
2.从…2024-1-3 文章目录 [2487. 从链表中移除节点](https://leetcode.cn/problems/remove-nodes-from-linked-list/)方法一调用栈方法二递归方法三翻转链表 2487. 从链表中移除节点 方法一调用栈
1.将所有节点按顺序压入栈中
2.从栈顶依次查看元素
3.当栈顶节点的值大于新链表表头的值将该节点插入新链表的表头
4.否则移除该节点 public ListNode removeNodes(ListNode head) {DequeListNode stack new ArrayDeque();while (head!null){stack.push(head);head head.next;}while (!stack.isEmpty()){if (headnull||stack.peek().valhead.val){stack.peek().next head;将该节点插入新链表的表头head stack.peek();//表头前移}stack.pop();}return head;}方法二递归
1.节点为空返回
2.不为空对右侧节点进行判断
3.比右侧节点小移除当前结点返回下一个结点
4.比右侧节点大返回当前结点 public ListNode removeNodes(ListNode head) {if (head null){return null;}head.next removeNodes(head.next);if (head.next!null head.val head.next.val){return head.next;}else {return head;}}方法三翻转链表
1.翻转链表、要求改为移除每一个左侧有一个更大数值的节点。
2.不断移除右结点除非右结点的值大于等于当前结点
3.再翻转回来 public ListNode removeNodes3(ListNode head) {head reverse(head);ListNode cur head;while (cur.next!null){if (cur.valcur.next.val){//当前值比右边值大删除右边结点cur.next cur.next.next;}else {cur cur.next;}}return reverse(head);//翻转回来}public ListNode reverse (ListNode head){//翻转链表ListNode dummy new ListNode();while (head!null){ListNode cur head;head head.next;cur.next dummy.next;dummy.next cur;}return dummy.next;}点击移步博客主页欢迎光临~