链表是继数组之后第二种使用得最广泛的通用存储结构。
链表机制灵活,用途广泛,可以取代数组,作为其他存储结构的基础,例如栈、队列。
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();
}
}
谢谢观赏,再见。