zoukankan      html  css  js  c++  java
  • java实现双端链表

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

      

  • 相关阅读:
    将帅问题
    堆栈(链栈)
    堆栈(基础实现原理 顺序栈)
    双向链表
    冒泡排序 (泛型版)
    maven
    jboss数据源配置
    仓库介绍,nexus的安装
    mave聚合继承
    mac mysql 安装
  • 原文地址:https://www.cnblogs.com/cugb-2013/p/3675440.html
Copyright © 2011-2022 走看看