题解 | #从单向链表中删除指定值的节点#

从单向链表中删除指定值的节点

https://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;

class ListNode{
    int val;
    ListNode next;
    ListNode(){};
    ListNode(int val){
        this.val = val;
    }
    ListNode(int val, ListNode next){
        this.val = val;
        this.next = next;
    }
}

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        List<Integer> list = new ArrayList<>();
        int n =in.nextInt();
        int[] nums = new int[(n-1)*2];
        int headVal = in.nextInt();
        ListNode head = new ListNode(headVal);
        ListNode pre = new ListNode(-1,head);
        for(int i=0 ; i<(n-1)*2 ; i++){
            nums[i] = in.nextInt();
            if(i%2 == 1){
                ListNode p = head;
                while(p.val != nums[i]){
                    p = p.next;
                }
                ListNode q = p.next;
                ListNode cur = new ListNode(nums[i-1]);
                p.next = cur;
                cur.next = q;

                }
        }
        int delete = in.nextInt();

            // while(head != null){
            //     System.out.print(head.val+" ");
            //     head = head.next;
            // }

            ListNode p=pre, q=p.next;
            while(q != null){
                if(q.val == delete){
                    p.next = q.next;
                    q.next = null;
                    q=p.next;
                }
                else{
                    p=p.next;
                    q=q.next;
                }
            }
            while(head != null){
                System.out.print(head.val+" ");
                head = head.next;
            }
        }
}

全部评论

相关推荐

10-28 17:30
已编辑
华东交通大学 Java
iori2333:这太正常了 我字节面了四五轮 没有一次是在官网投递 都是hr主动捞
秋招笔试记录
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务