题解 | 【模板】链表

【模板】链表

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

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {

    static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            this.val =x;
        }

    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别

        int n = in.nextInt(); // 操作的次数
        ListNode dummy = new ListNode(-1);
        in.nextLine();
        while (n-- > 0) {
            String line = in.nextLine();
            String[] arr = line.split(" ", -1);
            
            if (arr[0].equals("insert")) {
               
                insert(dummy, arr[1], arr[2]);
            }else if (arr[0].equals("delete")) {
                
                delete(dummy, arr[1]);
            }
        }
        print(dummy);
    }


    private static void insert(ListNode dummy, String xStr, String yStr) {
        int x = Integer.parseInt(xStr);
        int y = Integer.parseInt(yStr);
        ListNode cur = dummy;
        while (cur != null && cur.next != null) {
            if (cur.next.val == x) {
                //    插入
                ListNode node = new ListNode(y);
                node.next = cur.next;
                cur.next = node;
                return;
            }
            cur = cur.next;
        }
        ListNode node = new ListNode(y);
        cur.next = node;
    }

    private static void delete(ListNode dummy, String xStr) {
        int x = Integer.parseInt(xStr);
        ListNode cur = dummy;
        while(cur != null && cur.next != null) {
            if (cur.next.val == x) {
                cur.next = cur.next.next;
                return;
            }   
            cur = cur.next;  
        }
    }



    private static void print(ListNode head) {
        if (head.next == null) {
            System.out.println("NULL");
            return;
        }
        ListNode cur = head.next;

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

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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