链表练习(Java)

这篇博客主要介绍了在Java中进行链表操作的实践练习,包括删除指定值的节点、反转链表、找到链表的中间结点、寻找倒数第k个节点、合并有序链表、按值分割链表、删除重复结点、判断回文链表、查找链表公共结点和检测环等挑战。通过这些练习,可以深入理解和掌握链表的数据结构及其操作技巧。
摘要由CSDN通过智能技术生成

学习完链表之后,需要进行大量练习,从而熟能生巧。首先,我们建立一个基础链表,后续练习都建立在此基础上:

class Node {
   
    public int data;
    public Node next;
    public Node(int data) {
   
        this.data = data;
        this.next = null;
    }
}

public class MyLinkedList {
   
    public Node head;//保存单链表的头节点的引用

    public void addLast(int data) {
   
        Node node = new Node(data);
        if (this.head == null) {
   
            this.head = node;
            return;
        }
        Node cur = this.head;
        while (cur.next != null) {
   
            cur = cur.next;
        }
        cur.next = node;
    }
    public void disPlay() {
   
        Node cur = this.head;
        while (cur != null) {
   
            System.out.println(cur.data + " ");
            cur = cur.next;
        }
        System.out.println();
    }
    //查找是否包含关键字key是否在单链表中
    public boolean contains(int key) {
   
        Node cur = this.head;
        while (cur != null) {
   
            if (cur.data == key) {
   
                return true;
            }
            cur = cur.next;
        }
        return false;
    }
    //得到单链表长度
    public int size() {
   
        int count = 0;
        Node cur = this.head;
        while (cur != null) {
   
            count++;
            cur = cur.next;
        }
        return count;
    }
}
  1. 删除链表中等于给定值 val 的所有节点。
    public void removeAllVal(int val) {
   
        Node prev = this.head;
        Node cur = this.head.next; //代表要删除的节点
        while (cur != null) {
   
            if (cur.data == val) {
   
                prev.next = cur.next;
                cur = cur.next;
            } else {
   
                prev = cur
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值