单链表:
- 节点内容
- 下一个节点的引用
一个单链表实例:
public class LikeNode {
public int iData;
public double dData;
public LikeNode next;
public LikeNode(int iData, double dData) {
this.iData = iData;
this.dData = dData;
}
public void displayNode(){
System.out.println("{"+iData+","+dData+"}");
}
}
public class LikeList {
LikeNode first;
public void insertFirst(int i,double d){
LikeNode likeNode=new LikeNode(i,d);
first.next=likeNode;
this.first=likeNode;
}
public LikeNode deleteFirst(){
LikeNode temp=first;
this.first=first.next;
return temp;
}
public LikeNode find(int key){
LikeNode current=first;
while (current!=null){
if(current.iData==key){
return current;
}
current=current.next;
}
return null;
}
public LikeNode delete(int key){
LikeNode current=first;
LikeNode previous=first;
while (current!=null){
if (current.iData==key){
previous.next=current.next;
return current;
}
previous=current;
current=current.next;
}
return null;
}
public void displayList(){
System.out.println("list (first -->last) ");
LikeNode current=this.first;
while (current!=null){
current.displayNode();
current=current.next;
}
System.out.println();
}
}
链表的优点:
插入、删除 都比较快。不需要移动节点。
查找也和数组差不多(不按下标查找的情况下)
使用链表实现的队列:
public class QueueNode {
public int age;
public QueueNode previous;
public QueueNode next;
public QueueNode(int value) {
this.age=value;
}
}
public class LinkQueue {
private QueueNode first;
private QueueNode last;
public void queue(int value){
QueueNode queueNode=new QueueNode(value);
if (isEmpty()){
first=queueNode;
last=queueNode;
return;
}
this.first.previous=queueNode;
queueNode.next=this.first;
this.first=queueNode;
}
public QueueNode deQueue(){
if (isEmpty()){
return null;
}
QueueNode last1=this.last;
QueueNode previous= last1.previous;
if (previous!=null){
previous.next=null;
this.last=previous;
}else {
this.first=this.last=null;
}
return last1;
}
public boolean isEmpty(){
return first==null && last==null;
}
public static void main(String[] args) {
LinkQueue linkQueue=new LinkQueue();
for (int i=0;i<10;i++){
linkQueue.queue(i+10);
}
while (!linkQueue.isEmpty()){
QueueNode queueNode=linkQueue.deQueue();
System.out.println(queueNode.age);
}
}
}