单链表的反转

这道题老生常谈了,首先单链表的特点:

<1>单链表不要求逻辑上相邻的两个元素在物理位置上也相邻,因此不需要连续的存储空间。
<2>单链表是非随机的存储结构,即不能直接找到表中某个特定的结点。查找某个特定的结点时,需要从表头开始遍历,依次查找。

 示意图:

 代码实现:

class SingleLinkedList {
    private final HeroNode head = new HeroNode(0,"","");

    /**
     * 反转一个链表
     * @return 链表
     */
    public static HeroNode reverse(HeroNode head) {
        // 1.头节点为null
        if (head.next == null || head.next.next == null) {
            return head;
        }
        // 2.辅助指针
        HeroNode cur = head.next;
        HeroNode next = null;   // 临时变量
        HeroNode reverse = new HeroNode(0,"","");
        // 3.指针移动,将cur中的变量放入reverse
        while (cur != null) {
            next = cur.next;
            cur.next = reverse.next;
            reverse.next = cur;
            cur = next;
        }
        head.next = reverse.next;
        return reverse;
    } 

    public void list() {
        HeroNode temp = this.head;
        if (head.next == null) {
            System.out.println("HeroNode{ }");
        }
        while (temp.next != null){
            System.out.println(temp.next);
            temp = temp.next;
        }
    }

    public int size() {
        int count = 0;
        HeroNode temp = this.head;
        while (temp.next != null){
            count++;
            temp = temp.next;
        }
        return count;
    }
}

/**
 * 节点
 */
class HeroNode {
    int no;
    String name;
    String nickName;
    HeroNode next;  // 尾节点

    public HeroNode(int no, String name, String nickName) {
        this.no = no;
        this.name = name;
        this.nickName = nickName;
    }

    @Override
    public String toString() {
        return "HeroNode{" +
                "no=" + no +
                ", name='" + name + '\'' +
                ", nickName='" + nickName + '\'' +
                '}';
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值