题解 | #【模板】链表#

【模板】链表

http://www.nowcoder.com/practice/97dc1ac2311046618fd19960041e3c6f

import java.util.*;
public class Main{
    static LinkedList<Integer> list = new LinkedList<>();
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        String num = sc.nextLine();
        while(sc.hasNextLine()){
            String input = sc.nextLine().trim();
            if(input.equals(""))
                continue;
            String[] arr = input.split(" ");
            if(arr[0].equals("insert"))
                insert(Integer.valueOf(arr[1]),Integer.valueOf(arr[2]));
            else if(arr[0].equals("delete"))
                delete(Integer.valueOf(arr[1]));
        }
        if(list==null || list.isEmpty())
            System.out.println("NULL");
        else{
            for(Integer element:list){
                System.out.print((int)element);
                System.out.print(" ");
            }

        }      
    }
    public static void insert(int x,int y){
        int index = list.indexOf(x);
        if(index!=-1)
            list.add(index,y);
        else
            list.add(y);
    }
    public static void delete(int x){
        int index = list.indexOf(x);
        if(index!=-1)
            list.remove(Integer.valueOf(x));
    }
}

注意: 1.要考虑链表为null和内部元素为空情况 2.LinkedList可以根据元素获取序号index如indexOf(int x)函数 remove可以根据元素删除也可以根据序号删除。

全部评论

相关推荐

码农索隆:单休一个月少休息4天,一年就是48天,平时节假日,别人3天假期,单休的两天
点赞 评论 收藏
分享
07-09 18:33
门头沟学院 Java
这么逆天每年都有人去???&nbsp;填多益网申就是大型的服从性测试
鲁大牛:辅导员在群里发了这个公司我就申了一下。网申居然要写当场开摄像头写两篇不少于三百字的作文。太逆天了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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