数据结构-链表(双端链表)-2015

本文介绍了一种数据结构——双端链表,并提供了详细的Java实现代码。双端链表不仅支持头部操作,还支持尾部操作,具备插入和删除速度快等优点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

链表是继数组之后第二种使用得最广泛的通用存储结构。

链表机制灵活,用途广泛,可以取代数组,作为其他存储结构的基础,例如栈、队列。

ADT:抽象数据类型

链表的优点:

①插入和删除速度很快

②数组的大小是固定的,而链表不是


双端链表:

单链表是对头部节点的引用,在头部插入,头部删除;双端链表的特性是增加了对最后一个节点的引用。


代码:

节点类

public class Node {
	public int iKey;
	public String value;
	public Node next;
	
	public Node(int iKey, String value){
		this.iKey = iKey;
		this.value = value;
	}
	
	public void display(){
		System.out.println("key-->" + iKey + "; value-->" + value);
	}
}


双端链表:

/**
 * Program Name:
* Description:双端链表
* Methods:
* @version ver:1.0
*
* @see class:
* @exception class:
*
* @author name:
* Written Date:2015-3-1
*
* Modified No:
* Modified By:
* Modified Date:
* Modified Description:
 */
public class LinkList {
	private Node first;
	private Node last;
	
	public LinkList(){
		first = null;
		last = null;
	}
	
	public boolean isEmpty(){
		return (null == first);
	}
	
	public void insertFirst(int key, String value){
		Node node = new Node(key, value);
		if(null == first){
			first = node;
			last = node;       //双端链表
		}else{
			node.next = first;
			first = node;
		}
	}
	
	public Node deleteFirst(){
		if(null == first)
			return null;
		
		Node node = first;
		first = node.next;
		return node;
	}
	
	public void display(){
		System.out.println("first --- last: ");
		if(null == first){
			System.out.println(" ");
			return;
		}
		
		Node current = first;
		while(null != current){
			current.display();
			current = current.next;
		}
	}
	
	//查找指定节点
	public Node find(int key){
		if(null == first)
			return null;
		
		Node current = first;
		while(null != current){
			if(current.iKey == key)
				break;
			
			current = current.next;
		}
		
		return current;
	}
	
	public boolean deleteKey(int key){
		boolean flag = false;
		
		Node current = first;
		Node prev = first;
		
		if(null == first){
			return false;
		}else{
			
			while(current.iKey != key){
				if(null == current){
					return false;
				}
				
				prev = current;
				current = current.next;
			}
			
			flag = true;
		}
		
		
		if(first == current){
			first = first.next;
		}else{
			prev.next = current.next;
		}
		
		return flag;
	}
	
	//尾部插入
	public void insertLast(int key, String value){
		Node node = new Node(key, value);
		
		if(isEmpty()){
			first = node;
			last = node;
		}else{
			last.next = node;
			last = node;
		}
	}
	
	public static void main(String[] args){
		LinkList link = new LinkList();
		link.insertFirst(1, "a");
		link.insertFirst(2, "b");
		link.insertFirst(3, "c");
		
		link.insertLast(4, "d");
		link.insertLast(5, "e");
		link.insertLast(4, "f");
		
		link.display();
	}

}


谢谢观赏,再见。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值