自定义链表
//单链表,链表节点存放的是键值对
//链表节点
class Node{
public int key;
public int value;
public Node next;
public Node(int key, int value){
this.key = key;
this.value = value;
this.next = null;
}
public void showNode(){
System.out.println(key+"--->"+value);
}
}
//链表
class LinkList{
private Node first;
public LinkList(){
first = null;
}
public boolean isEmpty(){
return (first == null);
}
//前插
public void insertFirst(int key, int value){
Node tmp = new Node(key, value);
tmp.next = first;//注意理解
first = tmp;//注意理解
}
//后插
public void insertLast(int key, int value){
if(first == null){
first = new Node(key, value);
}else{
Node tmp = first;
while(tmp.next != null){
tmp = tmp.next;
}
tmp.next = new Node(key, value);
}
}
public Node deleteFirst(){
if(first == null){
return null;
}else{
Node tmp = first;
first = first.next;
return tmp;
}
}
public Node find(int key){
if(first == null){
return null;
}else{
Node tmp = first;
while(tmp.key != key){
if(tmp.next == null){
return null;
}else{
tmp = tmp.next;
}
}
return tmp;
}
}
public Node delete(int key){
if(first == null){
return null;
}else{
Node tmp = first;
Node pre = first;
while(tmp.key != key){
if(tmp.next == null){
return null;
}else{
pre = tmp;
tmp = tmp.next;
}
}
//while执行完能到这一步就说明tmp != null
if(tmp == first){//如果在第一个节点就找到了
first = first.next;
}else{
pre.next = tmp.next; ;
}
return tmp;
}
}
public void showLinkList(){
System.out.println("LinkList:");
Node tmp = first;
while(tmp != null){
tmp.showNode();
tmp = tmp.next;
}
System.out.println();
}
}
public class Main {
public static void main(String[] args){
LinkList list = new LinkList();
list.insertFirst(1, 111);//前插
list.insertFirst(2, 222);//前插
list.insertFirst(3, 333);//前插
list.insertLast(4, 444);//后插
list.showLinkList();//打印链表
//查找演示
Node tmp = list.find(3);
if(tmp == null){
System.out.println("Can't not find Node with key "+3);
}else{
System.out.print("Found Node with key "+tmp.key+": ");
tmp.showNode();
System.out.println();
}
//删除演示
Node tmp1 = list.delete(1);
if(tmp1 == null){
System.out.println("Can't not find Node with key "+1);
}else{
System.out.print("Deleted Node with key "+tmp1.key+": ");
tmp1.showNode();
System.out.println();
}
System.out.println();
while(!list.isEmpty()){
Node tmp2 = list.deleteFirst();
System.out.print("Deleted: ");
tmp2.showNode();
list.showLinkList();
}
System.out.println("LinkList is empty: "+list.isEmpty());
}
}
双端链表
仅仅是在单链表的基础上,在LinkList类里加了一个last引用,指向尾节点。
链栈、链队列
略。(直接使用上述链表容易实现,无非是增加、删除、获取、判空等)
对应的容器
LinkedList
有序链表
和普通单链表的实现的主要不同:插入的时候要保证是有序的。