算法通关村第一关——链表青铜挑战笔记

本文介绍了链表的基础知识,包括如何创建链表节点,遍历链表以获取长度,以及在链表中插入和删除节点的方法。插入操作涵盖首部、中部和尾部,删除操作涉及头节点、尾节点和中间节点。文章还提出了后续完善的方向,如单调递增的插入和删除操作。
摘要由CSDN通过智能技术生成

算法通关村第一关——链表青铜挑战笔记

创建链表

public class ListNode{
	public int val;
	public ListNode next;
}
	ListNode(int x){
		val = x;
		next = null;
	}

//创建
ListNode node1 = new ListNode(1);

遍历链表

public static int getListLength(Node head){
	int length = 0;
	Node node = head;
	while(node != null){
		length++;
		node = node.next;
	}
	return length;
}

链表插入

单链表的插入需要考虑三种情况:首部、中部和尾部。

  1. 在链表的表头插入

在这里插入图片描述

newNode.next = head;
head = newNode;
  1. 在链表的中间插入
    在这里插入图片描述
newNode.next = node(15).next;
node(15).next = newNode;
  1. 在链表的结尾插入结点
    在这里插入图片描述
node(40).next = newNode;

综上所述:链表插入的方法如下所示。

    /**
     * 链表插入
     * @param head          链表头节点
     * @param nodeInsert    待插入节点
     * @param position      待插入位置,从1开始
     * @return              插入后得到的链表头节点
     */
    public static Node insertNode(Node head, Node nodeInsert, int position){
        if(head == null){
            //这里可以认为待插入的结点就是链表的头结点,也可以抛出不能插入的异常
            return nodeInsert;
        }

        //已经存放的元素个数
        int size = getSize(head);
            if(position > size + 1 || position < 1){
            System.out.println("位置参数越界");
            return head;
        }

        //表头插入
        if(position == 1){
        nodeInsert.next = head;
        head = nodeInsert;
        return head;
        }

        Node curNode = head;
        int count = 1;
        //这里position被上面的size限制住了,不用考虑curNode = null
            while(count < position - 1){
            curNode = curNode.next;
            count++;
        }
        nodeInsert.next = curNode.next;
        curNode.next = nodeInsert;

        return head;
    }

链表删除

删除操作同样分为在删除头部元素,删除中间元素和删除尾部元素。

  1. 删除表头结点
    在这里插入图片描述
head = head.next
  1. 删除最后一个节点
    在这里插入图片描述
if(node(7).next == node(40)){
	node(7).next = null;
}
  1. 删除中间节点
    在这里插入图片描述
cur.next = cur.next.next;

综上所述:链表删除的方法如下所示。

/**
     *
     * @param head          链表头节点
     * @param position      删除节点位置,取值从1开始
     * @return              删除后的链表头节点
     */
    public static Node deleteNode(Node head, int position){
		if(head == null){
			return null;
		}
		int size = getSize(head);
		if(position > size || position < 1){
			System.out.println("输入的位置参数有误!");
			return head;
		}
		if(position == 1){
			return head.next;
		}

		Node curNode = head;
		int count = 1;
		while(count < position - 1){
			curNode = curNode.next;
			count++;
		}
		curNode.next = curNode.next.next;
		return head;
	}

后续完善

  1. 链表单调递增插入。
  2. 链表单调递增删除。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值