链表是一种在物理上非连续而在逻辑上具有连续性的数据结构,链表由一系列的节点组成,每个节点包含一个数据域,和下一个节点的指针域。相比于线性表的顺序结构链表具有方便的插入和删除操作的特性。
链表分为单链表,双端链表,有序链表,双向链表和有迭代器的链表。今天首先解释单链表。
一、单链表
单链表是最简单的链表形式,单链表具有增加节点,增,删,改,查,遍历和指定插入等操作。
单链表的java实现方式:
1、节点类
public class Node {
private String value; //数据域
private Node next; //指针域
public Node(String value){
this.value = value;
}
public void setNext(Node next){
this.next = next;
}
public Node getNext(){
return next;
}
public String showValue(){
return value;
}
}
2、链表类
public class LinkedList {
Node first;
public LinkedList(String value){
Node node = new Node(value);
this.first = node;
}
public LinkedList(){
}
public void addFirst(String value){
Node node = new Node(value);
node.setNext(first);
first = node;
}
public void show(){
if(isEmpty()){
System.out.println("Linked list is Empty!");
}else {
Node node = first;
while (node!=null) {
System.out.print(node.showValue()+" ");
node = node.getNext();
}
}
}
public boolean isEmpty(){
if(first==null){
return true;
}else {
return false;
}
}
public void del(String value){
if(isEmpty()){
return;
}else {
Node node1 = first;
Node node2 = first.getNext();
if(node1.showValue().equals(value)){
first = first.getNext();
}else {
while (node2!=null&&!node2.showValue().equals(value)) {
node1 = node2;
node2=node2.getNext();
}
if(node2!=null){
node1.setNext(node2.getNext());
}
}
}
}
public Node find(String value){
Node node = first;
while (node!=null) {
if(node.showValue().equals(value)){
return node;
}
node=node.getNext();
}
return null;
}
public void insertAfter(String value,String value2){
Node node = find(value);
if(node!=null){
Node n = new Node(value2);
n.setNext(node.getNext().getNext());
node.setNext(n);
}
}
}
3、测试类
public class Test {
public static void main(String[] args) {
LinkedList linkedList = new LinkedList();
LinkedList linkedList2 = new LinkedList("list2");
for(int i =0;i<10;i++){
linkedList.addFirst(i+"");
linkedList2.addFirst(i+"");
}
linkedList.show();
System.out.println();
linkedList2.show();
System.out.println();
System.out.println(linkedList.find(2+""));
System.out.println(linkedList.find(20+""));
System.out.println(linkedList2.find("list2"));
linkedList.del(0+"");
linkedList.del(10+"");
linkedList2.del(0+"");
linkedList2.del("list2");
linkedList.show();
System.out.println();
linkedList2.show();
System.out.println();
System.out.println();
linkedList.insertAfter(9+"", 99+"");
linkedList.show();System.out.println();
linkedList.insertAfter(19+"", 99+"");
linkedList.show();System.out.println();
}
}
4、测试结果
9 8 7 6 5 4 3 2 1 0
9 8 7 6 5 4 3 2 1 0 list2
Node@c17164
null
Node@1fb8ee3
9 8 7 6 5 4 3 2 1
9 8 7 6 5 4 3 2 1
9 99 7 6 5 4 3 2 1
9 99 7 6 5 4 3 2 1