当前位置:   article > 正文

牛客网:AB9 【模板】链表_牛客 ab9 测试用例

牛客 ab9 测试用例
  1. import sun.net.www.HeaderParser;
  2. import java.security.PrivateKey;
  3. import java.util.Scanner;
  4. /**
  5. * @author xienl
  6. * @description 链表
  7. * @date 2022/5/30
  8. */
  9. public class Solution {
  10. public static void main(String[] args) {
  11. MyNode node = new MyNode();
  12. Scanner scanner = new Scanner(System.in);
  13. int num = scanner.nextInt();
  14. scanner.nextLine();
  15. for (int i= 0; i < num; i++){
  16. String str = scanner.nextLine();
  17. String[] split = str.split("\\s+");
  18. if ("insert".equals(split[0])){
  19. node.insert(Integer.parseInt(split[1]), Integer.parseInt(split[2]));
  20. } else if ("delete".equals(split[0])){
  21. node.delete(Integer.parseInt(split[1]));
  22. }
  23. }
  24. node.print();
  25. }
  26. }
  27. /**
  28. * 链表类
  29. */
  30. class MyNode{
  31. private Node root; // 真实的链表
  32. public MyNode(){};
  33. public void insert(int x, int y){
  34. if (root == null){
  35. root = new Node(y);
  36. return;
  37. }
  38. Node head = new Node(-1, root);
  39. Node pre = head;
  40. while (pre.next != null && pre.next.value != x){
  41. pre = pre.next;
  42. }
  43. pre.next = new Node(y, pre.next);
  44. root = head.next;
  45. }
  46. public void delete(int x){
  47. Node head = new Node(-1, root); // 头节点
  48. Node pre = head;
  49. while (pre.next != null && pre.next.value != x){
  50. pre = pre.next;
  51. }
  52. if (head == null){
  53. return;
  54. }
  55. pre.next = pre.next == null ? null : pre.next.next;
  56. root = head.next;
  57. }
  58. public void print(){
  59. if (root == null){
  60. System.out.println("NULL");
  61. } else {
  62. root.print();
  63. }
  64. }
  65. /**
  66. * 链表
  67. */
  68. class Node{
  69. private int value;
  70. private Node next;
  71. public Node(){};
  72. public Node(int value){
  73. this.value = value;
  74. }
  75. public Node(int value, Node next){
  76. this.value = value;
  77. this.next = next;
  78. }
  79. public void print(){
  80. System.out.print(this.value + " ");
  81. if (this.next != null){
  82. this.next.print();
  83. }
  84. }
  85. }
  86. }

代码如上,可以直接编译哈。

讨论算法的话,可以私聊我哈,一起学习

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/467955
推荐阅读
相关标签
  

闽ICP备14008679号