707. 设计链表

题目具体描述见707

  1. class MyLinkedList {
  2. class Node {
  3. int val;
  4. Node pre, next;
  5. Node(){};
  6. Node(int val) {
  7. this.val = val;
  8. }
  9. Node(int val, Node pre, Node next) {
  10. this.val = val;
  11. this.pre = pre;
  12. this.next = next;
  13. }
  14. }
  15. Node head, tail;
  16. int size;
  17. public MyLinkedList() {
  18. head = new Node(-1);
  19. tail = new Node(-1);
  20. head.next = tail;
  21. tail.pre = head;
  22. size = 0;
  23. }
  24. public int get(int index) {
  25. if (index < 0 || index >= size)
  26. return -1;
  27. int reIndex = size - index - 1;
  28. //一个小优化,根据index决定从前往后查询还是从后往前查询
  29. if (index <= reIndex) {
  30. Node cur = head;
  31. while (index > 0) {
  32. cur = cur.next;
  33. index--;
  34. }
  35. return cur.next.val;
  36. } else {
  37. Node cur = tail;
  38. while (reIndex > 0) {
  39. cur = cur.pre;
  40. reIndex--;
  41. }
  42. return cur.pre.val;
  43. }
  44. }
  45. public void addAtHead(int val) {
  46. Node node = new Node(val, head, head.next);
  47. node.next.pre = node;
  48. head.next = node;
  49. size++;
  50. }
  51. public void addAtTail(int val) {
  52. Node node = new Node(val, tail.pre, tail);
  53. node.pre.next = node;
  54. tail.pre = node;
  55. size++;
  56. }
  57. public void addAtIndex(int index, int val) {
  58. if (index <= 0)
  59. addAtHead(val);
  60. else if (index == size)
  61. addAtTail(val);
  62. else if (index > size)
  63. return;
  64. else {
  65. int reIndex = size - index;
  66. //一个小优化,根据index决定从前往后查询还是从后往前查询
  67. if (index <= reIndex) {
  68. Node cur = head;
  69. while (index > 0) {
  70. cur = cur.next;
  71. index--;
  72. }
  73. Node node = new Node(val, cur, cur.next);
  74. node.next.pre = node;
  75. cur.next = node;
  76. size++;
  77. } else {
  78. Node cur = tail;
  79. while (reIndex > 0) {
  80. cur = cur.pre;
  81. reIndex--;
  82. }
  83. Node node = new Node(val, cur.pre, cur);
  84. node.pre.next = node;
  85. cur.pre = node;
  86. size++;
  87. }
  88. }
  89. }
  90. public void deleteAtIndex(int index) {
  91. if (index < 0 || index >= size)
  92. return;
  93. int reIndex = size - index - 1;
  94. //一个小优化,根据index决定从前往后查询还是从后往前查询
  95. if (index <= reIndex) {
  96. Node cur = head;
  97. while (index > 0) {
  98. cur = cur.next;
  99. index--;
  100. }
  101. cur.next = cur.next.next;
  102. cur.next.pre = cur;
  103. size--;
  104. } else {
  105. Node cur = tail;
  106. while (reIndex > 0) {
  107. cur = cur.pre;
  108. reIndex--;
  109. }
  110. cur.pre = cur.pre.pre;
  111. cur.pre.next = cur;
  112. size--;
  113. }
  114. }
  115. }
  116. /**
  117. * Your MyLinkedList object will be instantiated and called as such:
  118. * MyLinkedList obj = new MyLinkedList();
  119. * int param_1 = obj.get(index);
  120. * obj.addAtHead(val);
  121. * obj.addAtTail(val);
  122. * obj.addAtIndex(index,val);
  123. * obj.deleteAtIndex(index);
  124. */