206. Reverse Linked List[Easy]

206. Reverse Linked List

Given the head of a singly linked list, reverse the list, and return the reversed list.

Constraints:

  • The number of nodes in the list is the range [0, 5000].
  • -5000 <= Node.val <= 5000

Example
image

Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]

思路

利用临时变量,依次逆转每个节点

题解

  • 简易
        ListNode result = null;
        // 存头节点
        ListNode temp = head;
        // 存临时节点
        ListNode cur;

        while (temp != null) {
            // 取出当前节点,赋给临时节点
            cur = new ListNode(temp.val);
            // 把上一个节点赋给当前节点的next,首次应该是null
            cur.next = result;
            // 用当前节点替换上一个节点
            result = cur;

            // 遍历下一个节点
            temp = temp.next;
        }
        return result;
    }
  • 精简
    public ListNode reverseList(ListNode head) {
        ListNode result = null;

        while (head != null) {
            // 暂存临时变量
            ListNode next = head.next;
            // 把上一次的结果赋给当前节点的下一位
            head.next = result;
            // 当前节点为结果
            result = head;
            // 遍历下一个节点
            head = next;
        }
        return result;
    }
posted @ 2023-01-30 13:45  AaronTanooo  阅读(33)  评论(0)    收藏  举报