1 57 58 package com.Yasna.util; 59 60 import java.util.*; 61 62 72 public class LinkedList { 73 74 78 private LinkedListNode head = new LinkedListNode("head", null, null); 79 80 83 public LinkedList() { 84 head.next = head.previous = head; 85 } 86 87 92 public LinkedListNode getFirst() { 93 LinkedListNode node = head.next; 94 if (node == head) { 95 return null; 96 } 97 return node; 98 } 99 100 105 public LinkedListNode getLast() { 106 LinkedListNode node = head.previous; 107 if (node == head) { 108 return null; 109 } 110 return node; 111 } 112 113 118 public LinkedListNode addFirst(LinkedListNode node) { 119 node.next = head.next; 120 node.previous = head; 121 node.previous.next = node; 122 node.next.previous = node; 123 return node; 124 } 125 126 133 public LinkedListNode addFirst(Object object) { 134 LinkedListNode node = new LinkedListNode(object, head.next, head); 135 node.previous.next = node; 136 node.next.previous = node; 137 return node; 138 } 139 140 147 public LinkedListNode addLast(Object object) { 148 LinkedListNode node = new LinkedListNode(object, head, head.previous); 149 node.previous.next = node; 150 node.next.previous = node; 151 return node; 152 } 153 154 157 public void clear() { 158 LinkedListNode node = getLast(); 160 while (node != null) { 161 node.remove(); 162 node = getLast(); 163 } 164 165 head.next = head.previous = head; 167 } 168 169 175 public String toString() { 176 LinkedListNode node = head.next; 177 StringBuffer buf = new StringBuffer (); 178 while (node != head) { 179 buf.append(node.toString()).append(", "); 180 node = node.next; 181 } 182 return buf.toString(); 183 } 184 } 185 | Popular Tags |