单链表的增删改查

遍历单链表

  • 对于单链表,一定是从头开始逐个往后遍历,所以表头不能丢,不能出现’狗熊掰棒子’问题,丢失了表头的指针
  • 代码
public static int getListLength(Node head){
	int length = 0;
	Node node = head;
	while(node != null){
		length++;
		node = node.next;
	}
	return length;
}

单链表插入

在单链表的头部插入

头插法的图示

在这里插入图片描述

在单链表的中间插入

在这里插入图片描述

在单链表的尾部插入

在这里插入图片描述

代码构建

    /**
     *
     * @param head 传入头结点
     * @param insertNode 传入插入结点
     * @param position 待插入位置,默认第一个结点为1,根据位置来判断式哪种插入方式
     * @return
     */
    public static Node insertNode(Node head,Node insertNode,int position){
        if(head.next == null){
            head.next = insertNode;
        }
        int length = getLength(head);
        if(position > length + 1 || position < 1){
            System.out.println("位置参数越界");
            return head;
        }
//        表头插入
        if(position == 1){
            insertNode.next = head.next;
            head.next = insertNode;
            return head;
        }
//        表尾插入
        if(position == length + 1){
//            复制head
            Node pNode = head;
//            遍历到最后一位
            while(pNode.next != null){
                pNode = pNode.next;
            }
//            插入
            pNode.next = insertNode;
            return head;
        }
//        接下来就是表中插入了
        Node pNode = head;
        int count = 1;
//        如果我想插入到第n位,那么我应该让pNode指到n-1位
        while(count < position){
            count++;
            pNode = pNode.next;
        }
        insertNode.next = pNode.next;
        pNode.next = insertNode;
        return head;
    }

链表删除

头结点删除

在这里插入图片描述

尾结点删除

在这里插入图片描述

中间结点删除

在这里插入图片描述

代码构建

public static Node deleteNode(Node head,int position){
        if(head == null){
            return null;
        }
        int length = getLength(head);
        if(position > length || position < 1) {
            System.out.println("插入位置有问题");
            return head;
        }
        if(position == 1){
            head = head.next;
        }else{
            Node pNode = head;
            int count = 1;
            while(count < position - 1){
                count++;
                pNode = pNode.next;
            }
            pNode.next = pNode.next.next;
        }
        return head;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值