How do you reverse a singly linked list without recursion in Java?

Reverse a linked list

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 the links between nodes.

Examples:

Input: Head of following linked list
1->2->3->4->NULL
Output: Linked list should be changed to,
4->3->2->1->NULL

Input: Head of following linked list
1->2->3->4->5->NULL
Output: Linked list should be changed to,
5->4->3->2->1->NULL

Input: NULL
Output: NULL



Input: 1->NULL
Output: 1->NULL

Implementing Your Own Linked List on Interviews

Since using existing Java classes is now allowed on Programming Job interviews, you need to create your own to write code. For this example, I have created our own singly linked list class. Similar to java.util.LinkedListalso contains a nested static class Node, which represents a node in the linked list.

This class contains an integer attribute to hold the data part and another Node reference to point to the next one in the list. If you want to create a Generic linked list, you should replace int with T, a generic type, as shown here.

In order to demonstrate that our reverse method is working, we will not only have to create a linked list but also need to populate the linked list. In order to populate, you need to implement the add[] method on the singly linked list.

You have two choices, either add the element at the head or at the tail, adding an element to the head is easy as it doesn't require a traversal till the end but if you want to create a list that contains elements in the order they are added then we need to add nodes at the end of the linked list.

I have also created a print[] method to print all nodes of the singly linked list, separated by space. This method is very useful to demonstrate that our reverse method is actually working or not, as you can print the linked list before and after reversal.

If you struggle with implementing essential data structures like a linked list, binary tree, the hash table in your own code on any programming language like Java then I suggest you joinAlgorithms and Data Structures - Part 1 and 2courses on Pluralsight. They will not only help you to write your data structure but also how to calculate time and space complexity.





Algorithm –reverse single linked list in java [iterative algorithm]

  1. head variable denotes head of single linked list.
  2. Take couple of temporary variables
    • next = null
    • prev = null
  3. next = head.next [Step 1]
    • save reference of subsequent node in next variable
  4. head.next = prev[node reversed] [Step 2]
  5. prev = head [Step 3]
  6. head = next [head points to second node] [Step 4]

Fig 2: Reverse nodes in single linked list

Nowapply the algorithm to reverse the linked list. Once we apply the above algorithm to complete linked list, we will get the reverse linked list as shown in Fig 3

Fig 3: Reversed single linked list

Time complexity of algorithm is O[n].

“reverse linked list without recursion” Code Answer


recursive reverse linked list
csharp by Wandering Wolverine on Aug 22 2021 Comment
1
Source: leetcode.com
Add a Grepper Answer


C# queries related to “reverse linked list without recursion”

  • reverse linked list recursive
  • reverse linked list using recursion
  • recursively reverse linked list
  • java reverse linked list recursive
  • reverse a linked list recursive
  • reversing the linked list using recursion
  • reverse linked list recursion
  • reverse a linked list using recursion in java
  • reverse a doubly linked list recursively
  • recursive linked list reverse
  • reverse a linked list recrusion
  • reverse a singly linked list using recursion
  • reverse linkedlist recursive
  • how to reverse a linked list using recursion
  • reverse linked list using recursion in c
  • trace the reverse linked list using recursion in c++
  • reverse a linked list with recrusion
  • reverse linked list recursively
  • reverse the given singly linked list [non recursive]
  • recursive function to output and reverse linked list
  • can you reverse a linked list with recursion
  • how to recursively reverse a linked list python
  • reverse linked list without recursion
  • reverse linked list 2 recursive
  • recursive implementation of the reverse method on a linkedlist
  • print a linked list in reverse order recursion
  • reverse a linked list recursively c++
  • reverse doubly linked list using recursion
  • printing a linked list in reverse recursion
  • python reverse linked list recursive
  • gfg reverse linked list using recursion
  • recursviely reverse linked list
  • reverse a linked list iteratively and recursively in c++
  • display linked list in reverse order using recursion
  • reverse a linked list recursion
  • linked list reverse recursion
  • reverse linked list in recursion
  • recursive reverse linked list in c++
  • recursive reverse linked list python
  • reverse linked list using recursion in java
  • reverse the given singly linked list[recursive]
  • reverse a linked list recursivley
  • recursive reverse l inedlist
  • recursive reverse display singly linked list c++
  • recursion reverse k elements linked list
  • reverse linkedlist using recursion
  • reverse a linked list recursively
  • recursive reverse linked list
  • reversing a linked list using recursion
  • how to reverse a linked list recursively
  • reverse singly linked list recursively
  • reverse singly linked list using resursion
  • reverse linked list recursive java
  • reverse a linked list using recursion, iterative
  • reverse linked list using recursion in cpp
  • how do you reverse a singly linked list without recursion?
  • how to reverse a doubly linked list recursively
  • reverse a singly linked list recursively
  • how to reverse linked list using recursion
  • reverse a singly linked list using recursion.
  • reverse traversal in singly linked list recursive
  • how make reverse in singly linked list withp recursion
  • reverse a linked list with recrusion in c++
  • recursively reversing a linked list [a simple implementation]
  • reverse a linkedlist ecursive
  • reverse singly linked list without recursion
  • reverse recursive linked list c
  • recursive solution for reversing a singly linked list
  • reverse a linked list recursively in c
  • reverse linked list recursive js
  • reverse linkedlist recuroice
  • reverse a linked list iteratively
  • reverse a linked list java recursive
  • print linked list recursively in reverse
  • reverse linked list [pointer - recursive]
  • what is the best way to reverse the linked list recursive
  • recursively reverse a linked list
  • recursively reverse linked list java
  • reverse linke list using recursion
  • reverse linked list by recursion java
  • how to recursively reverse a linked list using c++ ?
  • reverse linked list recursive at k node
  • recursive method to reverse a linked list
  • linked list c++ print reverse by recursion
  • reverse the linked list in iterative manner
  • reverse linked list with recursion
  • how to reverse singly linked list in java with recursive function
  • display reverse linked list using recursion
  • recursive function to print reverse of a linked list c++
  • recursion to reverse a linked list
  • linked list reversal using recursion
  • reverse a linked list using recursion
  • reverse linked list recursive python
  • reverse linked list recursively
  • reverse linked list python recursive
  • reverse a linked list recursively python
  • reverse singly linked list using recursion
  • reverse linked list c recursive
  • linked list reverse recursive
  • reverse linked list recursive javascript
  • recursive reverse display in single linked list c++
  • reverse singly linked list recursively explanation
  • reverse a linked list using recursion in c
  • how to recursively reverse a linked list
  • recursive reversal of linked list
  • reverse a linked list using recursion in c++
  • reversing a linked list recursively
  • make a reverse method for linkedlist with recursive
  • trace the reverse linked list using recursion
  • recursive function to output and reverse linked list in c
  • reverse linked list using recursion c++
  • recursive code for reversing linked list in c++
  • reverse a linked list recursively code library
  • reverse linked list recursive c++
  • reverse a linked list js - recursive
  • how do you reverse a singly linked list without recursion
  • function to reverses order of items in a singly linked list using recursion
  • how to reverse a singly linked list using recursion
  • linked list with recursion reversed
  • reverse a linked list iteratively and recursively
  • reverse a linked list recursively java
  • recursively reversing a linked list
  • reverse a linked lsit recursively
  • recursive function used to reverse a singly linked list
  • reverse of a linked list using recursion
  • reverse a linked list in java using recursion
  • how to reverse a linked list using recursion in c
  • reversing linked list recursively
  • print reverse linked list recursive python
  • solution reverse a linked list recursion
  • reverse the given singly linked list[non-recursive]
  • reverse a linked list recursively cpp
  • linkedlist reverse recursively
  • recursive linked list reverse java
  • display linked list in reverse order c++ recursion
  • how to de a reverse linked list recursively

C


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include
#include
// A Linked List Node
struct Node
{
int data;
struct Node* next;
};
// Helper function to print a given linked list
void printList[struct Node* head]
{
struct Node* ptr = head;
while [ptr]
{
printf["%d —> ", ptr->data];
ptr = ptr->next;
}
printf["NULL\n"];
}
// Helper function to insert a new node at the beginning of the linked list
void push[struct Node** head, int data]
{
struct Node* newNode = [struct Node*]malloc[sizeof[struct Node]];
newNode->data = data;
newNode->next = *head;
*head = newNode;
}
// Reverses a given linked list by changing its `.next` pointers and
// its head pointer. Takes a pointer [reference] to the head pointer
void reverse[struct Node** head]
{
struct Node* previous = NULL; // the previous pointer
struct Node* current = *head; // the main pointer
// traverse the list
while [current != NULL]
{
// tricky: note the next node
struct Node* next = current->next;
current->next = previous;// fix the current node
// advance the two pointers
previous = current;
current = next;
}
// fix the head pointer to point to the new front
*head = previous;
}
int main[void]
{
// input keys
int keys[] = { 1, 2, 3, 4, 5, 6 };
int n = sizeof[keys]/sizeof[keys[0]];
struct Node* head = NULL;
for [int i = n - 1; i >=0; i--] {
push[&head, keys[i]];
}
reverse[&head];
printList[head];
return 0;
}

DownloadRun Code

Output:

6 —> 5 —> 4 —> 3 —> 2 —> 1 —> NULL

1. Introduction

In this tutorial, we'll implement two linked list reversal algorithms in Java.

Java Program to Reverse a singly linked list using recursion and Iteration

A linked list is a data structure which contains nodes, every node keep data and pointer to the next node. This way linked list grows and can store as many elements as much memory allows it. It's not like an array that requires a contiguous chunk of memory because here node can be stored at any memory location.

This structure means, adding and removing elements in a linked list is easy but searching an element is expensive because you need to traverse the entire list to find the element. It doesn't help even if you know that element is the 5th node or 6th node because you cannot access them by index like an array.

This is the biggest difference between an array and a linked list data structure. In the array, searching the index is O[1] operation but in linked list searching is O[n] operation.

It is said that a picture is worth a thousand word and it is very true in the case of problem-solving and understanding algorithms. If you are a visual learner, I strongly suggest checking out the Visualizing Data Structures and Algorithms in Java course which explains all fundamental data structures and algorithms with animations and interesting diagrams. Here are a diagram and a flowchart to reverse a singly linked list using recursion.


It divides the list into two parts first node and rest of the list,and then link rest to head in reverse order. It then recursively applies the same division until it reaches the last node, at that point whole linked list, is reversed.

Coming back to our code which represents a singly linked list in Java [see the next section], with limited operations. I have already removed some non-relevant code for performing different operations on a linked list likechecking if the linked list is cyclic or not, inserting an element at the middle, and removing the element. Since we don't need this code for reversing a linked list, I have simply deleted them for now.

This class is similar to theSinglyLinkedListclass, which we have seen in how to implement a linked list in Java using generics [seehere], with two more methods for reversing linked list using iteration and recursion.

The reverseRecursively[]methodreverses the linked list using recursion. It uses the call stack to store data, and once we reached tail, which becomes the new head for the reversed linked list, it starts adding nodes in reverse order. Look at some comments around those methods, which will make you understand the algorithm of reversing the linked list better.

ThereverseIteratively[]method reverses the linked list using the three-pointers approach and using loops, that's why it is called an iterative solution. It traverses through the linked list and adding nodes at the beginning of the singly linked list in each iteration. It uses three reference variables [pointers] to keep track of previous, current, and next nodes.

Btw, If you are not very familiar with a linked list data structure or want to learn more about linked list data structure, you should first read a good course on data structure and algorithm likeAlgorithms and Data Structures - Part 1 and 2on Pluralsight, one of the best course to learn data structure and algorithms.




Video liên quan

Bài Viết Liên Quan

Bài mới nhất

Chủ Đề