day4-2

前天学习了在c++中怎么使用单链表,我在网上学习了在Java中如何实现:
定义节点类:
class Node {
int data; // 存储数据
Node next; // 指向下一个节点的引用

// 构造函数
public Node(int data) {
    this.data = data;
    this.next = null;
}

}
定义链表类:
class SinglyLinkedList {
Node head; // 链表的头节点

// 在链表头部添加元素
public void addFirst(int data) {
    Node newNode = new Node(data);
    newNode.next = head;
    head = newNode;
}

// 在链表尾部添加元素
public void addLast(int data) {
    Node newNode = new Node(data);
    if (head == null) {
        head = newNode;
    } else {
        Node last = head;
        while (last.next != null) {
            last = last.next;
        }
        last.next = newNode;
    }
}

// 删除链表中的第一个元素
public void deleteFirst() {
    if (head == null) {
        return; // 链表为空,无法删除
    }
    head = head.next;
}

// 遍历链表
public void display() {
    Node current = head;
    while (current != null) {
        System.out.print(current.data + " -> ");
        current = current.next;
    }
    System.out.println("null");
}

}
使用:
public class Main {
public static void main(String[] args) {
SinglyLinkedList list = new SinglyLinkedList();

    // 添加元素
    list.addLast(1);
    list.addLast(2);
    list.addLast(3);
    list.addFirst(0);

    // 遍历并显示链表
    list.display();

    // 删除元素
    list.deleteFirst();
    list.display();
}

}

posted @   老汤姆233  阅读(7)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示