java实现双向链表

PS:双向链表(每个节点含有指向前一个节点的前驱与后一个节点的后继)

public class DoublyLinkedList {
	static class Node {
		private Object data;
		private Node prev;

		public Node getPrev() {
			return prev;
		}

		public void setPrev(Node prev) {
			this.prev = prev;
		}

		private Node next;

		public Node(Object value) {
			this.data = value;
		}

		public Object getData() {
			return data;
		}

		public void setData(Object data) {
			this.data = data;
		}

		public Node getNext() {
			return next;
		}

		public void setNext(Node next) {
			this.next = next;
		}

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

	private Node head;// 头节点

	public DoublyLinkedList() {
		head = new Node(null);
	}

	// 双向链表表头插入节点
	public void addFirst(Object value) {
		Node node = new Node(value);
		if (head.next == null) {
			head.next = node;
			node.prev = head;
		} else {
			node.prev = head;
			node.next = head.next;
			head.next.prev = node;
			head.next = node;
		}
		// head=node;
	}

	// 删除表头
	public void removeFirst() {
		Node node = head.next;
		if (node.next != null) {
			node.next.prev = head;
			head.next = node.next;
		}
	}

	// 顺序打印链表
	public void printList() {
		Node node = head.next;
		while (node != null) {
			System.out.print(node.data + " ");
			node = node.next;
		}
		System.out.println();
	}

	// 逆序打印链表
	public void reversePrintList() {
		Node node = head.next;
		Node tail = null;
		while (node.next != null) {
			node = node.next;
		}
		tail = node;
		// System.out.println(tail.data);
		while (tail.prev != null) {
			System.out.print(tail.data + " ");
			tail = tail.prev;
		}
		System.out.println();
	}

	public static void main(String[] args) {
		DoublyLinkedList linkedList = new DoublyLinkedList();
		for (int i = 0; i < 10; i++) {
			linkedList.addFirst(i);
		}
		System.out.println("顺序打印链表");
		linkedList.printList();
		System.out.println("逆序打印链表");
		linkedList.reversePrintList();
		System.out.println("依次删除头结点");
		for (int i = 0; i < 10; i++) {
			linkedList.removeFirst();
			linkedList.printList();
		}

	}
}

  

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值