Reverse Linked List Solutions in C++
Number 206
Difficulty Easy
Acceptance 62.7%
Link LeetCode
Solutions
C++ solution by haoel/leetcode
// Source : https://leetcode.com/problems/reverse-linked-list/// Author : Hao Chen// Date : 2015-06-09/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode(int x) : val(x), next(NULL) {}* };*/class Solution {public:ListNode* reverseList_iteratively(ListNode* head) {ListNode *h=NULL, *p=NULL;while (head){p = head->next;head->next = h;h = head;head = p;}return h;}ListNode* reverseList_recursively(ListNode* head) {if (head==NULL || head->next==NULL) return head;ListNode *h = reverseList_recursively(head->next);head->next->next = head;head->next = NULL;return h;}ListNode* reverseList(ListNode* head) {return reverseList_iteratively(head);return reverseList_recursively(head);}};
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/reverse-linked-list/description//// Author : liuyubobobo/// Time : 2017-11-15#include <iostream>using namespace std;struct ListNode {int val;ListNode *next;ListNode(int x) : val(x), next(NULL) {}};// Iterative// Time Complexity: O(n)// Space Complexity: O(1)class Solution {public:ListNode* reverseList(ListNode* head) {ListNode* pre = NULL;ListNode* cur = head;while(cur != NULL){ListNode* next = cur->next;cur->next = pre;pre = cur;cur = next;}return pre;}};int main() {return 0;}
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/reverse-linked-list/description//// Author : liuyubobobo/// Time : 2017-11-15#include <iostream>using namespace std;struct ListNode {int val;ListNode *next;ListNode(int x) : val(x), next(NULL) {}};// Recursive// Time Complexity: O(n)// Space Complexity: O(n)class Solution {public:ListNode* reverseList(ListNode* head) {if(head == NULL || head->next == NULL)return head;ListNode* rhead = reverseList(head->next);head->next->next = head;head->next = NULL;return rhead;}};int main() {return 0;}