• LeetCode Reverse Linked List


    绝对老题了,感觉已经重复了

    Reverse a singly linked list.

    click to show more hints.

    Hint:

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

    递归版本

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9  // 19:22
    10 class Solution {
    11 public:
    12     ListNode* reverseList(ListNode* head) {
    13         return reverseList(NULL, head);
    14     }
    15     
    16     ListNode* reverseList(ListNode* last, ListNode* head) {
    17         if (head == NULL) {
    18             return last;
    19         }
    20         ListNode* rest = head->next;
    21         ListNode* nhead = reverseList(head, rest);
    22         head->next = last;
    23         return nhead;
    24     }
    25 };

    非递归版本

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9  // 19:20
    10 class Solution {
    11 public:
    12     ListNode* reverseList(ListNode* head) {
    13         if (head == NULL) {
    14             return head;
    15         }
    16         ListNode* pre = NULL;
    17         ListNode* cur = head;
    18         while (cur != NULL) {
    19             ListNode* tmp = cur->next;
    20             cur->next = pre;
    21             pre = cur;
    22             cur = tmp;
    23         }
    24         return pre;
    25     }
    26 };
  • 相关阅读:
    797. 所有可能的路径
    1286. 字母组合迭代器
    216. 组合总和 III
    77. 组合
    784. 字母大小写全排列
    90. 子集 II
    78. 子集
    47. 全排列 II
    46. 全排列
    40. 组合总和 II
  • 原文地址:https://www.cnblogs.com/lailailai/p/4482965.html
Copyright © 2020-2023  润新知