单链表简单实现

这篇博客介绍了如何使用Java实现单链表的反转,包括头插法和尾插法,并提供了清空链表的方法。文章通过详细的代码示例展示了每个操作的过程,适合初学者了解链表操作的基础知识。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package linkede;

/**
 * (带头)单链表
 *
 * @author codelmh
 * @data 2021/12/9
 */
public class SingleLikedList<T> {
    private Node head; //记录头结点
    private Integer size = 0; // 链表大小


    /**
     * 链表反转
     * @param singleLikedList
     */
    public void reversalSingleLiked(SingleLikedList<T> singleLikedList){
        Node head = singleLikedList.head;// head 指向头结点
        Node pre = null;//存储头结点
        Node next;// 下一个节点
        //如果head  !=null 继续走
        while ( head != null) {
            next = head.next;//下一个节点
            head.next = pre; // 当前节点的next 指向 头结点
            pre = head; // 头结点指向当前
            head = next; // head 指向 下一个节点
        }
        singleLikedList.head = pre;
    }

    /**
     * 清空链表
     */
    public void clear(){
        this.size = 0;
        this.head = null;
    }
    /**
     * 尾插法
     * @param value
     */
    public void addLast(T value){
        Node node = new Node(value);
        // 用一个临时节点记录 head
        Node tail = head;
        if ( this.head == null){
            this.head = node;
        }else{
            // 获取尾部 这时 cur就是最后节点
            while ( tail.next != null){
                tail = tail.next;
            }
            tail.next = node;
        }
        size++;
    }
    /**
     * 头插法
     * @param value
     */
    public void addFirst(T value) {
        Node node = new Node(value);
        // 如果 头结点为空,则链表为空
        if (this.head == null)
            this.head = node;
        else{
            node.next = this.head;
            head = node;
        }
        this.size++;
    }

    /**
     * 链表是否空
     * @return
     */
    public boolean isEmpty(){
        return this.size == 0;
    }

    /**
     * 链表大小
     * @return
     */
    public int size(){
        return this.size;
    }

    private class Node {
        T value; //数据
        Node next; //指针

        // 节点初始化
        public Node(T value) {
            this.next = null;
            this.value = value;
        }
    }
}

本人小白一枚~  若有错误请指正!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值