Java中单链表的操作

这篇博客详细介绍了Java中单链表的四种基本操作:头插、头删、尾插和尾删。通过非引用类型的返回值(void)实现,并记录链表长度。文章提供了相应的代码实现,包括节点定义和具体的操作方法,旨在帮助读者理解链表的操作原理。
摘要由CSDN通过智能技术生成

单链表的操作,这次讲述头插、头删、尾插、尾删的另一种代码写法,返回值不再是引用类型(Node),而是void,还包括链表的长度。接下来,进行一一的介绍。

首先,我们先书写构成节点的代码,以下是代码:

public class Node {
   
    int value;
    Node next;
	
	//构造方法
    public Node() {
   
        value = 0;
        next = null;
    }

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

    public Node(int value,Node next) {
   
        
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java,单向链表是一种常见的数据结构,它由一系列节点组成,每个节点包含数据和指向下一个节点的指针。单向链表的特点是只能从头节点开始遍历到尾节点,不能反向遍历。 下面是一个简单的Java实现单向链表的例子: ```java public class Node { int data; // 节点数据 Node next; // 指向下一个节点的指针 public Node(int data) { this.data = data; this.next = null; } } public class LinkedList { Node head; // 链表头节点 public LinkedList() { this.head = null; } // 在链表尾部添加节点 public void add(int data) { Node newNode = new Node(data); if (head == null) { head = newNode; } else { Node current = head; while (current.next != null) { current = current.next; } current.next = newNode; } } // 在链表查找某个节点是否存在 public boolean contains(int data) { Node current = head; while (current != null) { if (current.data == data) { return true; } current = current.next; } return false; } // 删除链表第一个出现的指定节点 public void remove(int data) { if (head == null) { return; } if (head.data == data) { head = head.next; return; } Node current = head; while (current.next != null) { if (current.next.data == data) { current.next = current.next.next; return; } current = current.next; } } // 获取链表的节点数 public int size() { int count = 0; Node current = head; while (current != null) { count++; current = current.next; } return count; } } ``` 在上面的代码,Node类表示链表节点,LinkedList类表示单向链表。它包含了添加、查找、删除和获取节点数等常见操作。你可以根据自己的实际需求来对链表进行操作
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值