Given pointer to the head node of a linked list, the task is to reverse the linked
list. We need to reverse the list by changing links between nodes.
Examples:
Input : NULL
Output : NULL
Input : 1->NULL
Output : 1->NULL
Recommended: Please solve it on “PRACTICE” first, before moving on to the solution.
Iterative Method
Initialize three pointers prev as NULL, curr as head and next as NULL.
Iterate trough the linked list. In loop, do following.
// Before changing next of current,
// store next node
next = curr->next
// Now change next of current
// This is where actual reversing happens
curr->next = prev
filter_none
edit
play_arrow
brightness_4
// Iterative C++ program to reverse
// a linked list
#include<iostream>
using namespace std;
struct LinkedList
{
Node *head;
LinkedList()
{
head = NULL;
}
ll.reverse();
Output:
Given linked list
85 15 4 20
Reversed Linked list
20 4 15 85
Time Complexity: O(n)
Space Complexity: O(1)
Recursive Method:
1) Divide the list in two parts - first node and rest of the linked list.
2) Call reverse for the rest of the linked list.
3) Link rest to first.
4) Fix head pointer
Linked List Rverse
filter_none
edit
play_arrow
brightness_4
void recursiveReverse(struct Node** head_ref)
{
struct Node* first;
struct Node* rest;
/* empty list */
if (*head_ref == NULL)
return;
/* reverse the rest list and put the first element at the end */
recursiveReverse(&rest);
first->next->next = first;
brightness_4
// A simple and tail recursive C++ program to reverse
// a linked list
#include<bits/stdc++.h>
using namespace std;
struct Node
{
int data;
struct Node *next;
};
Output:
Given linked list
1 2 3 4 5 6 7 8
References:
http://cslibrary.stanford.edu/105/LinkedListProblems.pdf
Recommended Posts:
Can we reverse a linked list in less than O(n)?
Reverse a Linked List according to its Size
Reverse a Doubly Linked List | Set-2
Reverse a Doubly Linked List
Reverse a sublist of linked list
Reverse first K elements of given linked list
Reverse a circular linked list
Reverse a doubly circular linked list
Reverse a Doubly linked list using recursion
Print Reverse a linked list using Stack
Reverse a Linked List in groups of given size | Set 2
Reverse each word in a linked list node
Java Program for Reverse a linked list
Print reverse of a Linked List without actually reversing
Reverse a Linked List in groups of given size | Set 1
thumb_up
20
2.7
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.
Load Comments
Share this post!
#include<iostream.h>
int main ()
{
cout<<"hello world";
return 0;
}