题解 | #删除链表峰值#Java#

删除链表峰值

https://www.nowcoder.com/practice/30a06e4e4aa549198d85deef1bab6d25

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

/*
public class Test {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String s = scanner.nextLine();
        String substring = s.substring(1, s.length() - 1);
        String[] split = substring.split(",");
        ListNode node = new ListNode(Integer.parseInt(split[0]));
        ListNode head = node;
        for (int i = 1; i < split.length; i++) {
            ListNode listNode = new ListNode(Integer.parseInt(split[i]));
            node.next = listNode;
            node = node.next;
        }

        Solution solution = new Solution();
        ListNode listNode = solution.deleteNodes(head);
        StringBuilder stringBuilder = new StringBuilder("{");
        while (listNode!=null){
            stringBuilder.append(listNode.val+",");
            listNode = listNode.next;
        }
        stringBuilder.deleteCharAt(stringBuilder.length()-1);
        stringBuilder.append("}");
        System.out.println(stringBuilder.toString());
    }
}*/

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param head ListNode类
     * @return ListNode类
     */
    public ListNode deleteNodes(ListNode head) {
        if (head == null || head.next == null || head.next.next == null) {
            return head;
        }
        int len = 0;
        ListNode dump = new ListNode(0);
        dump.next = head;
        ListNode prev = dump, curr = dump;

        while (curr.next != null) {
            len++;
            curr = curr.next;
        }

        prev = dump.next;
        curr = prev.next;

        while (curr != null && curr.next != null) {
            ListNode next = curr.next;
            if (curr.val > prev.val && curr.val > next.val) {
                prev.next = next;
            } else {
                prev = curr;
            }
            curr = prev.next;
        }

        return dump.next;
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务