双链表的头插头删及尾插尾删操作

双链表的头插头删及尾插尾删操作:
定义链表:
Node类:

public class Node {
    int val;
    Node next;
    Node prev;

    Node(int val, Node next,Node prev){
        this.val=val;
        this.next=next;
        this.prev=prev;
    }
    Node(int val, Node next){
        this.val=val;
        this.next=next;
    }

    Node(int val){
        this(val,null,null);
    }
    @Override
    public String toString(){
        return String.format("Null{%d}",val);
    }
}

头插:

public class MyLinkedList2 {
    Node head = null;

    Node last = null;
    int size = 0;


    public Node pushFront(Node head,int val) {
        Node node = new Node(val);
        node.next = head;
        if(head!=null) {
            head.prev = node;
        }

        head = node;

        if (head.next == null) {
            last = head;
        }
        size++;
        return head;
    }

头删:

public Node popFront(Node head) {
        if (size == 0) {
            throw new RuntimeException("空了!");
        }


        head = head.next;
        if (head != null) {
            head.prev = null;
        } else {
            last = null;
        }
        size--;
        return head;
    }

尾插:

 public Node pushBack(Node head,int val) {
        Node node = new Node(val);
        if (last != null) {
            last.next = node;
            node.prev = last;
            last = node;
        } else {
            last = head = node;
        }
        size++;
        return head;
    }

尾删:

 public void popBack() {
        if (size == 0) {
            throw new RuntimeException("空了!");
        }
        if (last.prev != null) {
            last.prev.next = null;
            last = last.prev;

        } else {
            head = last = null;
        }
        size--;

    }
}

实现类:

public class UseList2 {
    public static void print(Node head) {
        Node cur = head;
        while (cur != null) {
            System.out.println(cur.val);
            cur = cur.next;
        }
    }

    public static void main(String[] args) {
        Node head = null;
        MyLinkedList2 h = new MyLinkedList2();
        head=h.pushFront(head,5);
        head=h.pushFront(head,4);
        head=h.pushFront(head,3);
        head=h.pushFront(head,2);
        head=h.pushFront(head,1);
        print(head);

       head=h.popFront(head);
        head=h.popFront(head);
        head=h.popFront(head);
        head=h.popFront(head);
        print(head);


        h.pushBack(head,4);
        h.pushBack(head,3);
        print(head);
        h.popBack();
        h.popBack();
        print(head);

    }
}

运行结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值