单链表的逆置、获取倒数第k个单链表节点的值的方法实现

本文深入探讨了单链表的节点类型定义,包括数据域和节点引用,并介绍了头节点的实现方式。此外,详细讲解了逆置单链表的算法逻辑及获取倒数第K个节点值的方法,为理解链表提供了实用的代码示例。
/**
     * 单链表的节点类型
     * @param <T>
     */
    static class Entry<T>{
        T data; // 链表节点的数据域
        Entry<T> next; // 下一个节点的引用

        public Entry(T data, Entry<T> next) {
            this.data = data;
            this.next = next;
        }
    }

    /**
     * 头节点的类型
     * @param <T>
     */
    static class HeadEntry<T> extends Entry<T>{
        int cnt; // 用来记录节点的个数

        public HeadEntry(int cnt, T data, Entry<T> next) {
            super(data, next);
            this.cnt = cnt;
        }
    }

    /**
     * 逆置单链表
     */
    public void reverse(){
        if(this.head.next == null){
            return;
        }

        Entry<T> cur = this.head.next.next;
        this.head.next.next = null;
        Entry<T> post = null;

        while(cur != null){
            post = cur.next;
            cur.next = head.next;
            head.next = cur;
            cur = post;
        }
    }

    /**
     * 获取倒数第K个单链表节点的值
     * 1.遍历一次链表,统计链表节点的个数length
     * 2.length - k
     */
    public T getLastK(int k){
        Entry<T> cur1 = this.head.next;
        Entry<T> cur2 = this.head;

        // cur1指向第一个节点,cur2指向正数第k个节点
        for (int i = 0; i < k; i++) {
            cur2 = cur2.next;
            if(cur2 == null){
                return null;
            }
        }

        // 当cur2到达末尾节点时,cur1指向的就是倒数第k个节点
        while(cur2.next != null){
            cur1 = cur1.next;
            cur2 = cur2.next;
        }

        return cur1.data;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值