双向链表的增删改查
class Node {
// 数据本身
Integer data;
// 上一个结点的地址
Node prev;
// 下一个结点的地址
Node next;
public Node() {
}
public Node(Integer data) {
this.data = data;
}
}
public class DoubleLinked {
//维护一个头结点,头结点不动
private Node head = new Node();
//返回头节点
public Node getHead(){
return head;
}
//显示链表(遍历)
public void list(){
if (head.next == null){
System.out.println("链表为空。。。");
return;
}
//因为头结点,不能动我们需要一个辅助变量帮我们遍历
Node temp = head.next;
while (true){
//判断是否走到了最后
if (temp == null){
break;
}
System.out.println(temp);
//将指针后移
temp = temp.next;
}
}
//添加节点到链表,默认添加的是到链表的最后一个位置
//先找到链表最后一个节点,把这个节点的next指向新增节点
//再让新增节点的上一个节点指向之前的最后一个节点
public void add(Node node){
//因为有节点不能动,
Node temp = head;
while (true){
//找到链表的表尾节点
if (temp == null){
break;
}
System.out.println(temp);
//如果没有找到最后,将temp后移
temp = temp.next;
}
//档退出while循环时,temp指针就到了最后
temp.next = node;
node.prev = temp;
}
//修改一个节点的内容
public void updata(Node node,Node newnode){
//判断链表是不是空
if (head.next == null){
System.out.println("链表为空。。。");
return;
}
//找到要修改的节点,根据data
//定义一个辅助变量
Node temp = head.next;
boolean flog = false;
while (true){
if (temp == null){
break;
}
if (temp.data == node.data){
flog = true;
break;
}
temp = temp.next;
}
//
if (flog){
//改变节点内容
temp.data = node.data;
}else {
System.out.println("没有找到" + node.data + "节点。。。");
}
}
//从双向列表删除一个节点
//1.找到节点
//2.删除
public void del(Integer data){
//判断链表是不是空
if (head.next == null){
System.out.println("链表为空。。。");
return;
}
Node temp = head.next;
boolean flog = false;
while (true){
if (temp == null){
break;// 已经找完一遍了,没找到
}
if (temp.data == data){
flog = true;
break;
}
temp = temp.next;
}
if (flog){
//删除
//删除第一个或最后一个节点会有null
temp.prev.next = temp.next;
if(temp.next != null){
temp.next.prev = temp.prev;
}
}else {
System.out.println("没有找到" + data + "结点...");
}
}
}