public class DoubleLinkedDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
//打印结点
StuNode stu1=new StuNode("钢铁侠","1000");
StuNode stu2=new StuNode("白","1001");
StuNode stu3=new StuNode("鸣人","1002");
StuNode stu4=new StuNode("佐助","1003");
StuNode stu5=new StuNode("美国队长","1004");
//创建链表
DoubleLinked Link=new DoubleLinked();
Link.add(stu1);
Link.add(stu2);
Link.add(stu3);
Link.add(stu4);
Link.add(stu5);
Link.show();
//按照学号修改元素,则学号保持不变
System.out.println();
StuNode stu6=new StuNode("绿巨人","1004");
Link.update(stu6);
Link.show();
//删除结点,根据姓名
System.out.println();
Link.del("绿巨人");
Link.show();
}
}
class StuNode{
protected String name;
protected String num;
protected StuNode next;
protected StuNode pre;
public StuNode(String name,String num) {
this.name=name;
this.num=num;
}
public String toString() {
return name+" - " +num;
}
}
class DoubleLinked{
//创建头节点结点
private StuNode head=new StuNode("","");
public StuNode getHeda() {
return head;
}
//尾插法添加元素
public void add(StuNode stu) {
StuNode temp=head;
while(temp.next!=null) {
temp=temp.next;
}
temp.next=stu;
stu.pre=temp;
}
//删除元素
public void del(String name) {
if(head.next==null) {
System.out.println("双向链表为空");
}
StuNode temp=head.next;
boolean flag=false;
while(temp!=null) {
if(temp.name==name) {
flag=true;
break;
}
temp=temp.next;
}
if(flag) {
temp.pre.next=temp.next;
//若没有if判断 则删除最后一个元素的时候会出现空指针异常
if(temp.next!=null)
temp.next.pre=temp.pre;
}else
{
System.out.println("此元素不存在");
}
}
//改元素,根据学号查找
public void update(StuNode stu) {
if(head.next==null) {
System.out.println("双向列表为空");
return;
}
StuNode temp=head.next;
boolean flag=false;
while(temp!=null) {
if(temp.num==stu.num) {
flag=true;
break;
}
temp=temp.next;
}
if(flag) {
temp.name=stu.name;
temp.num=stu.num;
}else {
System.out.println("双向链表里未找到相应的学号,跟新失败");
}
}
//查找元素,根据姓名查找
public boolean search(String name) {
if(head.next==null) {
System.out.println("双向链表为空");
return false;
}
StuNode temp=head.next;
boolean flag=false;
while(temp!=null) {
if(temp.name==name) {
flag=true;
}
temp=temp.next;
}
return flag;
}
//打印链表
public void show() {
StuNode temp=head.next;
while(temp!=null) {
System.out.println(temp);
temp=temp.next;
}
}
}
java中双向链表的增删改查
最新推荐文章于 2024-09-10 10:22:48 发布