第一关(青铜):链表定义及基本操作

1.1 什么是单链表

  1. 节点相互链接
  2. 每个节点最多一个后继节点

1.2常用的构造方法

public class ListNode {
    public int val;
    public ListNode next;

    ListNode(int x) {
        val = x;        //节点参数
        next = null;    //下一个节点    
    }
}
ListNode listnode=new ListNode(1);

1.3链表节点的插入

 public static Node insertNode(Node head, Node nodeInsert, int position) {
        if (head == null) {
        //这里可以认为待插入的结点就是链表的头结点,也可以抛出不能插入的异常
            return nodeInsert;
        }
        //已经存放的元素个数
        int size = getLength(head);
        if (position > size+1  || position < 1) {
            System.out.println("位置参数越界");
            return head;
        }

        //表头插入
        if (position == 1) {
            nodeInsert.next = head;
            // 这里可以直接 return nodeInsert;还可以这么写:
            head = nodeInsert;
            return head;
        }

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

        return head;
    }

个人理解:在这段代码中,可以了解到对于一个节点的插入,最重要的是在中间插入时,先获取需要插入的位置的后面一部分的链表,否则会造成当前位置节点后方链接消失。

1.4删除节点

public static Node deleteNode(Node head, int position) {
        if (head == null) {
            return null;
        }
        int size = getListLength(head);
        //思考一下,这里为什么是size,而不是size+1
        if (position > size || position <1) {
            System.out.println("输入的参数有误");
            return head;
        }
        if (position == 1) {
            //curNode就是链表的新head
            return head.next;
        } else {
            Node preNode = head;
            int count = 1;
            while (count < position - 1) {
                preNode = preNode.next;
                count++;
            }
            Node curNode = preNode.next;
            preNode.next = curNode.next;
        }
        return head;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值