LeetCode Reverse Linked List C++

206. Reverse Linked List

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?

Approch

1.题目很不错,特地记录下来。

Code

1.迭代式

class Solution {
 public:
     ListNode* reverseList(ListNode* head) {
         ListNode* cur = head, *p = nullptr;
         while (cur) {
             cur = cur->next;
             head->next = p;
             p = head;
             head = cur;
         }
         return p;
     }
 };
  1. 递归式
 class Solution {
 public:
     ListNode* reverseList(ListNode* head) {
         if (head == nullptr || head->next == nullptr)return head;
         ListNode*p = reverseList(head->next);
         head->next->next = head;
         head->next = nullptr;
         return p;
     }
 };

猜你喜欢

转载自blog.csdn.net/WX_ming/article/details/81989296
今日推荐