【java】【数据结构】java单链表 插入 删除 遍历

快来打我* 2022-10-11 00:48 268阅读 0赞
  1. package wwr;
  2. public class LinkedList<T> {
  3. //结点类
  4. public class Node {
  5. private T data;
  6. private Node next;
  7. public Node(T data, Node next) {
  8. this.data = data;
  9. this.next = next;
  10. }
  11. public Node(T data) {
  12. this(data, null);
  13. }
  14. public T getData() {
  15. return this.data;
  16. }
  17. public void setData(T data) {
  18. this.data = data;
  19. }
  20. }
  21. //成员变量
  22. private Node head;
  23. private int size;
  24. //构造函数
  25. public LinkedList() {
  26. this.head = null;
  27. this.size = 0;
  28. }
  29. //插入
  30. public void add(T data, int index) {
  31. if(index < 0 || index > this.size) {
  32. System.out.println("Index is error");
  33. }
  34. Node node = new Node(data);
  35. if(index == 0) {
  36. node.next = this.head;
  37. this.head = node;
  38. this.size ++;
  39. return;
  40. }
  41. Node pre = this.head;
  42. for(int i = 0; i < index - 1; i++) {
  43. pre = pre.next;
  44. }
  45. node.next = pre.next;
  46. pre.next = node;
  47. this.size ++;
  48. }
  49. //删除
  50. public void remove(T data) {
  51. if(head == null) {
  52. System.out.println("No element to remove");
  53. return;
  54. }
  55. if(head != null && head.data.equals(data)) {
  56. head.next = head.next.next;
  57. this.size--;
  58. }
  59. Node cur = this.head;
  60. while(cur != null && cur.next != null) {
  61. if(cur.next.data.equals(data)) {
  62. cur.next = cur.next.next;
  63. this.size--;
  64. }
  65. else
  66. cur = cur.next;
  67. }
  68. }
  69. //遍历
  70. public void print() {
  71. Node node = head;
  72. System.out.print(node.getData());
  73. while(node.next != null) {
  74. node = node.next;
  75. System.out.print(" " + node.getData());
  76. }
  77. System.out.print("\n");
  78. }
  79. //主函数
  80. public static void main(String[] args) {
  81. LinkedList<Integer> linked = new LinkedList();
  82. for(int i = 0; i < 10; i++) {
  83. linked.add(10 - i, i);
  84. linked.print();
  85. }
  86. linked.add(33, linked.size);
  87. linked.print();
  88. linked.add(33, 0);
  89. linked.print();
  90. linked.add(33, 6);
  91. linked.print();
  92. linked.remove(33);
  93. linked.print();

注:头结点下标为0

发表评论

表情:
评论列表 (有 0 条评论,268人围观)

还没有评论,来说两句吧...

相关阅读