【算法】【线性表】【链表】反转链表

1  题目

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

示例 1:

输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]

示例 2:

示例 3:

输入:head = []
输出:[]

提示:

  • 链表中节点的数目范围是 [0, 5000]
  • -5000 <= Node.val <= 5000

2  解答

复制代码
/**
 * Definition for ListNode
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param head: n
     * @return: The new head of reversed linked list.
     */
    public ListNode reverse(ListNode head) {
        // write your code here
        ListNode resHead = new ListNode(head.val);
        while (head.next != null) {
            head = head.next;
            // 新建节点保存当前节点信息
            ListNode node = new ListNode(head.val);
            // 把当前节点的下一个节点指向头节点
            node.next = resHead;
            // 头节点指向当前新节点
            resHead = node;
        }
        return resHead;
    }
}
复制代码

上边的空间相当于又创建了一份新的,再来个不产生新空间的头插法:

复制代码
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverse(ListNode head) {
        // 参数校验
        if (head == null || head.next == null) {
            return head;
        }
        // 采用头插法进行插入
        ListNode preNode = new ListNode(0);
        preNode.next = head;

        while (head.next != null) {
            ListNode nextNode = head.next;
            head.next = nextNode.next;
            nextNode.next = preNode.next;
            preNode.next = nextNode;
        }
        return preNode.next;
    }
}
复制代码

加油。

加油。

posted @   酷酷-  阅读(10)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示