概括

  • 一种物理存储上非连续、非顺序的存储结构
  • 由一系列节点组成,可以再运行时动态生成
  • 每个节点包括两个部分:数据域;指针域

image.png

特点

  • 数据存储不要求连续空间,不限制容量
  • 数据的逻辑顺序通过指针链接次序实现
  • 从链表头部依次访问后面的节点
  • 在链表表头插入数据的时间复杂度是O(1)

数据结构5.svg

优缺点

  1. 插入删除数据速度快
  2. 查询数据效率低

    实现

    链表实现

    1. public class LinkedDemo {
    2. public static void main(String[] args) {
    3. MyLinkedList myLinkedList = new MyLinkedList();
    4. myLinkedList.insert(3, 0);
    5. myLinkedList.insert(7, 1);
    6. myLinkedList.insert(9, 2);
    7. myLinkedList.insert(5, 3);
    8. myLinkedList.insert(6, 1);
    9. myLinkedList.remove(0);
    10. myLinkedList.print();
    11. }
    12. public static class MyLinkedList {
    13. public Node head;
    14. public Node last;
    15. public int size;
    16. public void insert(int data, int index) {
    17. if (index < 0 || index > size) {
    18. throw new IndexOutOfBoundsException("超出链表节点范围");
    19. }
    20. Node n = new Node(data);
    21. if (size == 0) {
    22. // 插入第一个值
    23. head = n;
    24. last = n;
    25. } else if (index == 0) {
    26. // 开头插入
    27. n.next = head;
    28. head = n;
    29. } else if (index == size) {
    30. // 结尾插入
    31. last.next = n;
    32. last = n;
    33. } else {
    34. // 中间插入
    35. Node node = get(index - 1);
    36. n.next = node.next;
    37. node.next = n;
    38. }
    39. size++;
    40. }
    41. public Node remove(int index) {
    42. if (index < 0 || index >= size) {
    43. throw new IndexOutOfBoundsException("超出链表节点范围");
    44. }
    45. Node remove;
    46. if (index == 0) {
    47. remove = head;
    48. head = head.next;
    49. } else if (index == size - 1) {
    50. last = get(size - 1);
    51. remove = last.next;
    52. last.next = null;
    53. } else {
    54. Node node = get(index - 1);
    55. Node next = node.next;
    56. node.next = next.next;
    57. remove = next;
    58. }
    59. size--;
    60. return remove;
    61. }
    62. public Node get(int index) {
    63. if (index < 0 || index >= size) {
    64. throw new IndexOutOfBoundsException("超出链表节点范围");
    65. }
    66. Node n = head;
    67. for (int i = 0; i < index; i++) {
    68. n = n.next;
    69. }
    70. return n;
    71. }
    72. public void print() {
    73. Node node = head;
    74. while (node != null) {
    75. System.out.println(node.id);
    76. node = node.next;
    77. }
    78. }
    79. }
    80. /**
    81. * 链表节点
    82. */
    83. public static class Node {
    84. public Node(int id) {
    85. this.id = id;
    86. }
    87. public int id;
    88. public Node next;
    89. }
    90. }