Last active
October 20, 2019 18:44
-
-
Save marta-krzyk-dev/a0871a4a80f6183b053a8769d2c3c089 to your computer and use it in GitHub Desktop.
Reverse a linked list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Solved problem: https://leetcode.com/problems/reverse-linked-list/ | |
/** | |
* Definition for singly-linked list. | |
* struct ListNode { | |
* int val; | |
* ListNode *next; | |
* ListNode(int x) : val(x), next(NULL) {} | |
* }; | |
*/ | |
#include <iostream> | |
using namespace std; | |
class Solution { | |
public: | |
void PrintList(ListNode* list) | |
{ | |
while (list != NULL) | |
{ | |
cout << list->val << " -> "; | |
list = list->next; | |
} | |
cout << "NULL" << endl; | |
} | |
ListNode* reverseList(ListNode* head) { | |
if (head == NULL || head->next == NULL) | |
return head; | |
ListNode* current = head->next; | |
ListNode* newNode = head; | |
newNode->next = NULL; | |
while (current != NULL) | |
{ | |
ListNode* newNodeTemp = newNode; | |
newNode = new ListNode(current->val); //Create node to add to the beginning of list | |
newNode->next = newNodeTemp; //Attach the result reverted list to the new beginning node | |
PrintList(newNode); | |
current = current->next; //Move to the next node | |
} | |
cout << "Result:" <<endl; | |
PrintList(newNode); | |
return newNode; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://leetcode.com/problems/reverse-linked-list/
Complexity: O(n-1)