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

      

  • 相关阅读:
    PEP8 Python 编码规范整理
    github操作
    重零开始,写一个股票交易项目(1)
    矢量地图质量检查现状与需求(2篇)
    导航数据质量评价相关
    测绘数据国内外现状概述
    机器的反叛-机器的智能会超越人类吗?
    标签要素调用CSS样式优先级说明
    内存碎片概念及主要避免方式
    关于年终述职总结
  • 原文地址:https://www.cnblogs.com/cugb-2013/p/3675440.html
Copyright © 2011-2022 走看看