双向链表
在单链表的基础上,每个节点增加了一个pre属性指向前一个节点。
因为单链表只有next指针,因此只能单向遍历。而双向链表可以从前或从后遍历。另外也可以自我删除,也就是不用借助被删节点的前一个节点进行删除,直接靠自己就行。
增删改查
节点增加了pre指向前一个节点
//双向链表的节点
class StudentNode2{
public int no;
public String name;
StudentNode2 next;
StudentNode2 pre;
public StudentNode2(int no, String name) {
this.no = no;
this.name = name;
}
@Override
public String toString() {
return "StudentNode{" +
"no=" + no +
", name='" + name + '\'' +
'}';
}
}
先遍历找到链表中的最后一个元素,再分别连上next和pre
//向链表中增加元素,直接加在末尾
public void add(StudentNode2 node){
//遍历链表,找到链表的最后
StudentNode2 temp=head;
while (true){
if (temp.next==null){
break;
}else if(temp.next.no==node.no){
throw new RuntimeException("重复添加!");
}
//遍历链表
temp=temp.next;
}
//temp指向链表最后一个元素,向temp后添加新元素
temp.next=node;
node.pre=temp;
}
找到添加位置的前一个,然后node.next=temp.next;连上后续不丢失,temp.next=node;与前面连接,node.pre = temp;反向连接,如果是加在链表的最末尾,后面是null,node.next有个空指针异常的问题,因此要加个判断。
//向链表中有顺序的添加元素,如果编号重复,添加失败
public void addByOrder(StudentNode2 node){
//根据编号找到需要添加的位置
StudentNode2 temp=head;
while (true){