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

链表的定义和创建

链表是一种物理存储单元上非连续、非顺序的存储结构,数据元素的逻辑顺序是通过链表中的指针链接次序实现的。链表中的每一个元素如下图所示的结构:

链表的节点在java中的定义方式:

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

        Node(int x) {
            val = x;
            next = null;
        }
    }

链表的增删改查

1.增

public static Node toucha(Node head,Node insertNode){
        if(head == null){
            insertNode = head;
        }else{
            insertNode.next = head.next;
            head.next = insertNode;
        }
        return head;
    }
 public static Node weicha(Node head,Node insertNode){
        if(head == null){
            insertNode = head;
        }else{
            Node cur = head;
            while(cur.next!=null){
                cur = cur.next;
            }
            cur.next = insertNode;
        }
        return head;
    }

上述代码分别为头插法和尾插法

2.删

public static void delete(Node head,int val){
        if(head == null){
            return;
        }else{
            Node cur = head;
            while(cur.next.data == val){
                cur = cur.next;
            }
            cur.next = cur.next.next;
        }
    }

3.改

public static void modify(Node head,int position,int val){
        if(head == null){
            return;
        }else{
            int count = 1;
            Node cur = head;
            while(count != position){
                count++;
                cur = cur.next;
            }
            cur.data = val;
        }
    }

4.查``

public static int check(Node head,int position){
        if(head == null){
            return 0;
        }else{
            int count = 1;
            Node cur = head;
            while(count != position){
                count++;
                cur = cur.next;
            }
            return cur.data;
        }
    }

注意,上述的增删改查只是最基本的实现,并没有考虑越界以及空指针的问题。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值