Thanks to visit codestin.com
Credit goes to www.educative.io

...

/

Reverse a Singly Linked List

Reverse a Singly Linked List

Reverse the singly linked list and return the head of the reversed linked list.

Statement

Given the head of a singly linked list, reverse the linked list and return its new or updated head.

Example

Consider the following linked list:

Codestin Search App Codestin Search App head Codestin Search App 7 Codestin Search App Codestin Search App 14 Codestin Search App Codestin Search App 21 Codestin Search App Codestin Search App 28 Codestin Search App Codestin Search App NULL Codestin Search App

Return the pointer to the reversed linked list as shown in the figure:

Codestin Search App Codestin Search App head Codestin Search App 28 Codestin Search App Codestin Search App 21 Codestin Search App Codestin Search App 14 Codestin Search App Codestin Search App 7 Codestin Search App Codestin Search App NULL Codestin Search App

Sample input

[7, 14, 21, 28]

Expected output

[28, 21, 14, 7]

Try it yourself #

main.cpp
LinkedList.cpp
LinkedListNode.cpp
#include "LinkedList.cpp"
using namespace std;
LinkedListNode* Reverse(LinkedListNode* head) {
//TODO: Write - Your - Code
}

Solution 1

If the linked list only contains 0 or 1 node, then the current list can be returned as it is. If there are two or more nodes, then the iterative solution starts with two node pointers:

  • First pointer: points to the head of the input linked list.
  • Second pointer: It points to the head’s next node.

We then set the next of the first pointer to NULL. It becomes the last node in the new reversed linked list. The first pointer always points to the ...