LeetCode算法 -- 反转链表(第5题)

一、题目描述

在这里插入图片描述

二、编写代码

2.1 编写一个 ListNode 类

package question5;

/**
 * @description: 链表的节点类
 * @author: hyr
 * @time: 2020/3/27 10:04
 */
public class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
    }

    @Override
    public String toString() {
        return "ListNode{" +
                "val=" + val +
                '}';
    }
}

2.2 编写 Solution 类

package question5;


/**
 * @description: 链表反转
 * @author: hyr
 * @time: 2020/3/27 9:57
 */
public class Solution {
    public static void main(String[] args) {
        // 创建链表
        ListNode header = new ListNode(0);
        ListNode node1 = header;
        for (int i = 1; i < 6; i++) {
            node1.next = new ListNode(i);
            node1 = node1.next;
        }


        // 展示链表
        System.out.println("反转前的链表为:");
        showList(header);

        System.out.println();

        // 反转链表并展示
        System.out.println("反转后的链表为:");
        reverseList(header);
        showList(header);

    }

    /**
     * 反转链表函数
     */
    private static void reverseList(ListNode header) {
        // 如果当前链表为空,或者只有一个节点,无需反转,直接返回
        if (header == null || header.next == null) {
            return;
        }

        ListNode point = header.next;
        ListNode next = null;
        ListNode reverseHead = new ListNode(0);

        while (point != null) {
            next = point.next;
            point.next = reverseHead.next;
            reverseHead.next = point;
            point = next;
        }

        header.next = reverseHead.next;
    }

    /**
     * 展示链表
     */
    private static void showList(ListNode header) {
        header = header.next;
        while (header != null) {
            System.out.println(header);
            header = header.next;
        }
    }
}

2.3 执行结果

反转前的链表为:
ListNode{val=1}
ListNode{val=2}
ListNode{val=3}
ListNode{val=4}
ListNode{val=5}

反转后的链表为:
ListNode{val=5}
ListNode{val=4}
ListNode{val=3}
ListNode{val=2}
ListNode{val=1}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值