206. Reverse Linked List

Problem:

Reverse a singly linked list.

Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

Follow up:

A linked list can be reversed either iteratively or recursively. Could you implement both?

思路

保存一个prev指针和next指针,分别指向head的前一个和后一个结点,只需让head重新指向prev即可。

Solution (C++):

ListNode* reverseList(ListNode* head) {
    using L = ListNode*;
    L prev = NULL, next = NULL;
    while (head) {
        next = head->next;
        head->next = prev;
        prev = head;
        head = next;
    }
    return prev;
}

性能

Runtime: 8 ms  Memory Usage: 7.7 MB

思路

Solution (C++):


性能

Runtime: ms  Memory Usage: MB

思路

Solution (C++):


性能

Runtime: ms  Memory Usage: MB

posted @ 2020-04-22 22:59  littledy  阅读(86)  评论(0编辑  收藏  举报