博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java实现双端链表
阅读量:6239 次
发布时间:2019-06-22

本文共 1633 字,大约阅读时间需要 5 分钟。

PS:双端链表(持有对最后一个节点的引用,允许表尾操作与表头操作等效的功能)

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();	}}

  

转载于:https://www.cnblogs.com/cugb-2013/p/3675440.html

你可能感兴趣的文章