Node类
//链表结构
public class Node {
//数据
public long data;
//指针,连接下个结点
public Node next;
public Node(long value){
this.data=value;
}
public void display(){
System.out.print(data+" ");
}
}
链表的常用方法
public class LinkList {
//头结点
private Node first;
//构造方法
public LinkList(){
first=null;
}
//每次添加都添加在开头
public void insertFirst(long value){
Node node = new Node(value);
node.next=first;
first=node;
}
//删除头结点
public Node deleteFirst(){
Node temp = first;
first=temp.next;
return temp;
}
//遍历
public void display(){
Node cur = first;
while (cur!=null){
cur.display();
cur=cur.next;
}
System.out.println();
}
//根据值查找结点
public Node find(long value){
Node cur = first;
while (cur.data!=value){
if (cur.next==null){
return null;
}
cur=cur.next;
}
return cur;
}
//删除指定值
public Node delete(long value){
Node cur = first;
Node pre = first;
while (cur.data!=value){
if (cur.next==null){
return null;
}
pre = cur;
cur = cur.next;
}
if (cur==first){
first=first.next;
}
pre.next = cur.next;
return cur;
}
}