Leetcode 反转链表

本文最后更新于:2022年3月23日 晚上

地址:https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/6/linked-list/43/

题目

反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

我的解决方案

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode *newHead = NULL;
        //不断取出和向后移动头节点,并将头节点连接到新头节点后面
        while (head != NULL) {
            //单独取出下一个节点
            ListNode *next = head->next;
            //将头节点连接到新头节点后面
            head->next = newHead;
            newHead = head;
            //向后移动头节点
            head = next;
        }
        return newHead;
    }
};

Leetcode 反转链表
https://mxy493.xyz/2019022750370/
作者
mxy
发布于
2019年2月27日
许可协议