Skip to content

Instantly share code, notes, and snippets.

@marta-krzyk-dev
Last active October 20, 2019 18:44
Show Gist options
  • Save marta-krzyk-dev/a0871a4a80f6183b053a8769d2c3c089 to your computer and use it in GitHub Desktop.
Save marta-krzyk-dev/a0871a4a80f6183b053a8769d2c3c089 to your computer and use it in GitHub Desktop.
Reverse a linked list
// 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;
}
};
@marta-krzyk-dev
Copy link
Author

marta-krzyk-dev commented Oct 20, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment