public class Test {
private int size;//链表的长度
private Node head;//链表头结点
//链表的结点类
private class Node{
private int number;
private Node next;
public Node(int number){
this.number=number;
}
}
public Node getHead(){
return head;
}
public Test(){
size=0;
head=null;
}
//链表头结点添加结点
public void addHead(int number){
Node newHead=new Node(number);
if(head==null){
head=newHead;
}else{
newHead.next=head;
head=newHead;
}
size++;
}
//链表结点查找
public Node findNode(int number){
Node newNode=head;
while(newNode!=null){
if(newNode.number==number)return newNode;
newNode=newNode.next;
}
return null;
}
//链表结点的删除
public void deleteNode(int num){
if(size==0){
System.out.println("The list is null");
}else{
Node deleteNode=head;
Node earlyNode=head;
while(deleteNode.number!=num){
if(deleteNode!=null){
earlyNode=deleteNode;
deleteNode=earlyNode.next;
}
}
if(deleteNode==null){
System.out.println("The number that you want to delete is not exit!");
}else if(deleteNode==head){
head=head.next;
size--;
}else{
earlyNode.next=deleteNode.next;
size--;
}
}
}
//链表的便遍历
public void display(){
Node newHead=head;
while(newHead!=null){
System.out.println(newHead.number);
newHead=newHead.next;
}
}
public static void main(String args[]){
Test test=new Test();
test.addHead(1);
test.addHead(2);
test.addHead(3);
test.addHead(4);
System.out.println(test.getHead());
System.out.println("The number that you want to delete is+ "+test.findNode(2).number);
test.display();
test.deleteNode(2);
test.display();
}
}
输出结果:
Test$Node@6b97fd
The number that you want to delete is+ 2
4
3
2
1
4
3
1