《剑指 Offer》——15、反转链表

    技术2022-07-11  84

    1. 本题知识点

    链表

    2. 题目描述

    输入一个链表,反转链表后,输出新链表的表头。

    3. 解题思路

    创建一个新链表,将原链表用头插法插入新链表,最后返回新链表。

    4. 代码

    public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } } public class Solution { /** * 输入一个链表,反转链表后,输出新链表的表头。 * @param head * @return */ public ListNode ReverseList(ListNode head) { // 反转链表的头结点 ListNode revHead = new ListNode(-1); // 当前结点的后继结点 ListNode next; // 头插法 while (head != null) { next = head.next; head.next = revHead.next; revHead.next = head; head = next; } return revHead.next; } }
    Processed: 0.012, SQL: 9