java實現雙端鏈表

PS:雙端鏈表(持有對最後一個節點的引用,容許表尾操做與表頭操做等效的功能)java

public class DoubleLinkedList {
	//節點類
        static class Node {
		public Object data;
		public Node next;

		public Node(Object dd) {
			data = dd;
		}

		@Override
		public String toString() {
			return String.valueOf(data);
		}
	}

	public Node head;//頭結點
	public Node tail;//尾節點

	public DoubleLinkedList() {
		head = null;
		tail = null;
	}

	public boolean isEmpty() {
		return (head == null);
	}

	// 表頭插入
	public void insertFirst(double dd) {
		Node newLink = new Node(dd);
		if (isEmpty()) {// 第一次插入節點
			tail = newLink;
		}
		newLink.next = head;
		head = newLink;
	}

	// 表尾插入
	public void insertLast(double dd) {
		Node newLink = new Node(dd);
		if (isEmpty()) {
			head = newLink;
		} else {
			tail.next = newLink;
		}
		tail = newLink;
	}

	// 刪除表頭
	public void deleteFirst() {
		head = head.next;
		if (head.next == null) {
			tail = null;
		}
	}

	public void displayList() {
		System.out.print("List (first--->last)");
		Node current = head;
		while (current != null) {
			System.out.print(current.data + " ");
			current = current.next;
		}
		System.out.println();
	}

	public static void main(String[] args) {
		DoubleLinkedList linkedList = new DoubleLinkedList();
		for (int i = 0; i <= 30; i += 5) {
			// 頭插
			linkedList.insertFirst(i);
		}
		System.out.println("頭插");
		linkedList.displayList();
		// 刪除表頭數據
		linkedList.deleteFirst();
		linkedList.displayList();
		linkedList = new DoubleLinkedList();
		for (int i = 0; i <= 30; i += 5) {
			// 尾插
			linkedList.insertLast(i);
		}
		System.out.println("尾插");
		linkedList.displayList();
		linkedList.deleteFirst();
		linkedList.displayList();
	}
}    
相關文章
相關標籤/搜索