java语言数据结构(单链表)

前言

不得承认java应用的广泛,所以毅然决定java版本的数据结构和算法专题还是要坚决更新。每日更新2题,希望学习的小伙伴可以关注一波跟上,评论区欢迎讨论交流。

实现原理

  1. 节点(Node):链表的基本构建单元是节点,每个节点包含两部分:数据和指向下一个节点的指针。

class Node {
    int data;
    Node next;

    public Node(int data) {
        this.data = data;
        this.next = null;
    }
}
  1. 头指针(Head Pointer):链表的起始节点被称为头节点。头指针是指向链表第一个节点的指针。通过头指针,可以访问整个链表。

  2. 尾节点(Tail Node):链表中最后一个节点称为尾节点。它的指针通常指向NULL,表示链表的结束。

  3. 指针连接:链表中的节点通过指针相互连接。每个节点的指针指向下一个节点,形成一个链式结构。

动画演示过程

Linked List Stack Visualization

头插法

// 定义节点类
class Node {
    int data;
    Node next;

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

// 定义单链表类
class LinkedList {
    private Node head;

    public LinkedList() {
        this.head = null;
    }

    // 在链表头部插入节点
    public void prepend(int data) {
        Node newNode = new Node(data);
        newNode.next = head;
        head = newNode;
    }

    // 打印链表
    public void printList() {
        Node current = head;
        while (current != null) {
            System.out.print(current.data + " ");
            current = current.next;
        }
        System.out.println();
    }
}

// 测试单链表头插法
public class Main {
    public static void main(String[] args) {
        LinkedList list = new LinkedList();
        list.prepend(3); // 链表:3
        list.prepend(5); // 链表:5 -> 3
        list.prepend(7); // 链表:7 -> 5 -> 3
        list.printList(); // 打印链表:7 5 3
    }
}

尾插法

// 定义节点类
class Node {
    int data;
    Node next;

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

// 定义单链表类
class LinkedList {
    private Node head;

    public LinkedList() {
        this.head = null;
    }

    // 在链表尾部插入节点
    public void append(int data) {
        Node newNode = new Node(data);
        if (head == null) {
            head = newNode;
            return;
        }
        Node current = head;
        while (current.next != null) {
            current = current.next;
        }
        current.next = newNode;
    }

    // 打印链表
    public void printList() {
        Node current = head;
        while (current != null) {
            System.out.print(current.data + " ");
            current = current.next;
        }
        System.out.println();
    }
}

// 测试单链表尾插法
public class Main {
    public static void main(String[] args) {
        LinkedList list = new LinkedList();
        list.append(3); // 链表:3
        list.append(5); // 链表:3 -> 5
        list.append(7); // 链表:3 -> 5 -> 7
        list.printList(); // 打印链表:3 5 7
    }
}

  • 8
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值