【DS】链表基本操作

1、头插

如果原链表不为空,要插入的节点的下一个节点就是原来链表的头节点,新链表的头节点就是要插入的节点;
如果原链表为空,直接插入,头节点就是要插入的节点
在这里插入图片描述

public  void pushFront(Node node){
        if(head!=null) {
            node.next = this.head;
            this.head=node;
        }else {
            this.head=node;
        }
    }

2、尾插

如果 原链表为空,尾插同头插
如果原链表不为空,找到链表最后一个结点,最后一个结点的下一个结点就是要插入的结点
在这里插入图片描述

//查找链表最后一个节点,前提是链表中至少有一个节点
     private Node curlast(){
        if(this.head==null){
            throw new Error();
        }
        Node cur = this.head;
        while(cur.next != null) {
            cur = cur.next;
        }
         return cur;
     }

//尾插
    public void  pushBack(Node node){
        if(this.head==null){
            this.head=node;
        }else {
            Node node1 = curlast();
            node1.next = node;

        }
    }

3、头删

如果原链表不为空,头删就是让原链表的头结点的下一个节点为新链表的头结点
在这里插入图片描述

 public  void popFront(){
        if(this.head == null){
            throw new Error();
        }else{
            this.head = this.head.next;
        }
    }

4、尾删

如果原链表不为空,尾删就是让原链表的倒数第二个结点的下一个节点为空
在这里插入图片描述

//找倒数第二个节点
private Node curLastLast(){
        Node cur1 = null;
        while(cur1.next.next != null  ){
            cur1 = cur1.next;
        }
        return cur1;
    }
    //尾删
    public  void  popBack(){
        if(this.head == null){
            throw new Error();
        }else {
            Node node2 = curLastLast();
            node2.next = null;
        }
    }

5、打印链表

public void display(){
        //如何通过循环,遍历链表的每一个节点
        Node cur = this.head;
        while (cur !=null) {
            System.out.println(cur.value);
            cur=cur.next;

        }
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值