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}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章