题解 | 【模板】链表

【模板】链表

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

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        in.nextLine();
        LinkList list = new LinkList();
        while (in.hasNextLine()) { // 注意 while 处理多个 case
            String[] line = in.nextLine().split(" ");
            if (line[0].equals("insert")) {
                list.insert(Integer.valueOf(line[1]), Integer.valueOf(line[2]));
            }
            if (line[0].equals("delete")) {
                list.delete(Integer.valueOf(line[1]));
            }
        }
        list.print();
    }
}

class LinkList {
    private ListNode root;
    public LinkList() {
        this.root = new ListNode(0);
    }

    public boolean isEmpty() {
        return root.next == null;
    }

    public void insert(int x, int y) {
        ListNode ptr = root;
        ListNode nodeToIns = new ListNode(y);
        while (ptr.next != null) {
            if (ptr.next.val == x) {
                nodeToIns.next = ptr.next;
                ptr.next = nodeToIns;
                return;
            }
            ptr = ptr.next;
        }
        ptr.next = nodeToIns;
    }

    public void delete (int numToDel) {
        ListNode ptr = root;
        while (ptr.next != null) {
            if (ptr.next.val == numToDel) {
                ptr.next = ptr.next.next;
                return;
            }
            ptr = ptr.next;
        }
    }

    public void print() {
        if (root.next == null) {
            System.out.println("NULL");
            return;
        }
        ListNode ptr = root;
        while (ptr.next != null) {
            System.out.print(ptr.next.val);
            ptr = ptr.next;
        if (ptr.next != null)System.out.print(" ");
        }
    }

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

}

全部评论

相关推荐

01-29 15:45
已编辑
华中科技大学 前端工程师
COLORSN:可以试一下,小厂看技术栈是不是很落后,如果太拉胯就别去,个人认为有实习氛围比你自己琢磨要高效不少,然后就是小厂其实也有可能会问的很难,这都比较难说,还是看自己项目含金量够不够,寒假还能不能推进学习再选择,毕竟去实习过年就10天假了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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