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

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

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

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int nodeSum=sc.nextInt();
        ListNode head=new ListNode(sc.nextInt(),null);

        int count=0;
        while(count<nodeSum-1){ //hasNext()无法返回false
            int first=sc.nextInt();
            int second=sc.nextInt();
            Insert(head,first,second);
            count++;

        }
        int k=sc.nextInt();


        ListNode vhead=new ListNode(0,head);
        ListNode index=vhead;
        while(index!=null&&index.next!=null){
            if(index.next.key==k){
                index.next=index.next.next;
            }
            index=index.next;
        }

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

    }

    public static void Insert(ListNode head,int first,int second){
        ListNode index=head;
        while(index!=null){
            if(index.key==second){
                ListNode temp=index.next;
                index.next=new ListNode(first,temp);
                return;
            }
            index=index.next;
        }

    }
}


class ListNode{
    int key;
    ListNode next;

    public ListNode(int key,ListNode next){
        this.key=key;
        this.next=next;
    }
}

全部评论

相关推荐

07-04 21:23
已编辑
东莞城市学院 后端
秋招和春招只收到几个中大厂的笔试,本人比较菜,感觉大厂的笔试太难,算法题不能全部做出来就没过了,但是CVTE和小天才的感觉不是很难,基本上都做出来了,笔试还是挂了。Boss上投了Java后端开发都没有回音,boss上有面试机会都是C#工控软件开发方向的,但是这个方向不太懂,资料又少,面试的表现有点差,现在还是想看看Java这边,面试的时候比较有把握点。想请教一下,这份简历还有什么问题,一直没什么机会,还有什么地方要修改的。
程序员小白条:学历太差,民办和公办,外包还得区分的,这个学历+这个简历,没的办法,除非你有人脉,太难了,这环境,何况你都毕业了,连一段实习都没,肯定没公司会挑选了,没竞争力,开发才招几个人,跟你竞争的可不是二本,三本的人哦,何况你在二本,三本里面也排名不高
投递小天才等公司7个岗位
点赞 评论 收藏
分享
06-10 23:36
已编辑
首都经济贸易大学 C++
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-09 12:20
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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