package Linke;
public class DoubleLinkeTest {
public static void main(String[] args) {
DoubleLinke linke=new DoubleLinke();
People people1=new People("张三",1);
People people2=new People("李四",2);
People people3=new People("王五",3);
People people4=new People("赵六",4);
People people5=new People("小朱",2);
int n=4;
//增加结点
linke.add(people1);
linke.add(people2);
linke.add(people3);
linke.add(people4);
//打印结果
linke.print();
//删除结点
linke.delete(people3);
//打印结果
System.out.println("删除名为"+people3.name+"的节点:");
linke.print();
//查找节点并输出到控制台
System.out.println("查找标号为"+n+"的结点:");
System.out.println(linke.seek(n));
//改节点内容
linke.update(people5);
//打印结果
System.out.println("更改编号为"+people5.no+"的节点的名字为"+people5.name);
linke.print();
}
}
class DoubleLinke{
People head;
public DoubleLinke() {
head=new People();
}
//增添方法
public void add(People people){
People temp=head;
//这里是对链表进行遍历
while (temp.next!=null) {
//这里把temp=temp.next放到while语句块的前面,因为如果放到后面,最后一个结点就遍历不到了。
temp=temp.next;
if(temp.no==people.no){
System.out.println(people+"已经存在,无法添加!");
return;
}
}
temp.next=people;
people.pre=temp;
}
//删除方法
public void delete(People people){
People temp=head;
while (temp.next!=null) {
temp=temp.next;
if(temp.no==people.no){
temp.pre.next=temp.next;
//因为要删除的节点可能是最后一个,所以要判断是否下一个是null,否则会在删除最后一个时报空指针异常
if(temp.next!=null){
temp.next=temp.pre;
}
return;
}
}
System.out.println("未找到要删除节点");
}
//更新方法
public void update(People people){
People temp=head;
while (temp.next!=null) {
temp=temp.next;
if(temp.no==people.no){
temp.name=people.name;
return;
}
}
System.out.println("未找到要更改节点");
}
//搜索方法
public People seek(int n){
People temp=head;
while (temp.next!=null) {
temp=temp.next;
if(temp.no== n){
return temp;
}
}
System.out.println("未找到标号为"+n+"的节点");
return null;
}
//打印链表内容
public void print(){
People temp=head;
while (temp.next!=null) {
temp=temp.next;
System.out.println(temp);
}
}
}
class People{
String name;
int no;
People next;
People pre;
public People() {
}
public People(String name, int no) {
this.name = name;
this.no = no;
}
public String toString(){
return "{no="+no+",name="+name+"}";
}
}
执行结果: