Java代码 循环链表的经典实现(JAVA) _经典 循环链表的经典实现(JAVA) _的_02

  1. public class LinkedListNode {//链表节点
  2.  
  3. public LinkedListNode previous;//前一节点
  4. public LinkedListNode next;//后一节点
  5. public Object object;//节点中存的值
  6.  
  7.  
  8. public long timestamp;
  9.  
  10.  
  11. public LinkedListNode(Object object, LinkedListNode next, LinkedListNode previous)
  12. {
  13. this.object = object;
  14. this.next = next;
  15. this.previous = previous;
  16. }
  17.  
  18.  
  19. public void remove() {//删除自己
  20. previous.next = next;
  21. next.previous = previous;
  22. }
  23.  
  24.  
  25. public String toString() {
  26. return object.toString();
  27. }
  28. }
  29.  
  30. import java.util.*;
  31.  
  32.  
  33. public class LinkedList {//循环链表
  34.  
  35. //头指针,哑的,第一个节点的前面,最后一个节点的后面
  36. private LinkedListNode head = new LinkedListNode("head", null, null);
  37.  
  38.  
  39. public LinkedList() {
  40. head.next = head.previous = head;
  41. }
  42.  
  43.  
  44. public LinkedListNode getFirst() {//获取循环链表的第一个节点
  45. LinkedListNode node = head.next;
  46. if (node == head) {
  47. return null;
  48. }
  49. return node;
  50. }
  51.  
  52.  
  53. public LinkedListNode getLast() {//获取循环链表的最后一个节点
  54. LinkedListNode node = head.previous;
  55. if (node == head) {
  56. return null;
  57. }
  58. return node;
  59. }
  60.  
  61.  
  62. public LinkedListNode addFirst(LinkedListNode node) {//将节点插入到链表的第一个位置,头节点之后.
  63. node.next = head.next;
  64. node.previous = head;
  65. node.previous.next = node;
  66. node.next.previous = node;
  67. return node;
  68. }
  69.  
  70.  
  71. public LinkedListNode addFirst(Object object) {//将值插入到链表的第一个位置,头节点之后.
  72. LinkedListNode node = new LinkedListNode(object, head.next, head);
  73. node.previous.next = node;
  74. node.next.previous = node;
  75. return node;
  76. }
  77.  
  78. public LinkedListNode addLast(Object object) {//将值插入到链表的最后一个位置,头节点之前
  79. LinkedListNode node = new LinkedListNode(object, head, head.previous);
  80. node.previous.next = node;
  81. node.next.previous = node;
  82. return node;
  83. }
  84.  
  85.  
  86. public void clear() {//清空循环链表
  87. //Remove all references in the list.
  88. LinkedListNode node = getLast();
  89. while (node != null) {
  90. node.remove();
  91. node = getLast();
  92. }
  93.  
  94. //Re-initialize.
  95. head.next = head.previous = head;
  96. }
  97.  
  98. public String toString() {
  99. LinkedListNode node = head.next;
  100. StringBuffer buf = new StringBuffer();
  101. while (node != head) {
  102. buf.append(node.toString()).append(", ");
  103. node = node.next;
  104. }
  105. return buf.toString();
  106. }
  107. }