zoukankan      html  css  js  c++  java
  • 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();
    		}
    
    	}
    }
    

      

  • 相关阅读:
    2020系统综合实践 第3次实践作业
    2020系统综合实践 第2次实践作业
    2020系统综合实践 第1次实践作业
    WireShark组 2019 SDN大作业
    2019 SDN阅读作业
    第07组 Beta版本演示
    OO第四单元总结
    OO第三单元总结
    OO第二单元总结
    OO第一单元总结
  • 原文地址:https://www.cnblogs.com/cugb-2013/p/3675442.html
Copyright © 2011-2022 走看看