Photo by Thought Catalog on Unsplash

Before we get into the problem. I have published an ebook. A compilation of 100 Java(Interview)Programming problems which have been solved . I have given clear explanation and the code in the book.

Trust me when I say, this will be a kick start for you to achieve the job at your dream company.

Click on this link to get you to the landing page. It is completely free when you use kindle amazon. Take a look at it.

Given a string as LinkedList (where each node has a character), reverse the LinkedList

Input String: M->i->k->e->NULL

Output: e->k->i->M->NULL

Input String: b->r->e->a->k->NULL

Output: k->a->e->r->b->NULL

Code:

public SchNode func(SchNode str){

// write your code here

if(str==null)

return null;

SchNode prev = null;

SchNode current = str;

SchNode next = null;

while (current != null) {

next = current.nextNode;

current.nextNode = prev;

prev = current;

current = next;

}

str = prev;

return str;

}

}

Explanation:

The problem is to reverse the given input list str.

The solution is to use another temporary list that access each element of the input list and the another temporary list that stores the accessed element in the reversed order. The final manipulated list is returned as output.

  • The input list str is passed to the function func(SchNode str)
  • If the input list is empty then null is returned as output.
  • The temporary node variables prev and next are declared and initialized with null and current is declared and assigned with the input list str.
  • A while loop is used that repeats the procedure until the end of the input list str.
  • The current node’s nextNode is assigned to the next
  • And prev is assigned to current’s nextNode.
  • Next node is assigned to the current.
  • Using the above three steps the nodes in the list are reversed.
  • Once the end of the list is reached the prev is assigned to str.
  • The str list is returned as output.

Conclusion

You can follow House of Codes to receive updates when we post new coding challenges. Also you could send us your solutions or your ideas for any coding challenge. We would be thrilled to read them. ;)

Author : Architha Harinath

Editor : Akshay Ravindran

Code -> Understand-> Repeat is my motto. I am a Data Engineer who writes about everything related to Data Science and Interview Preparation for SDE.

Code -> Understand-> Repeat is my motto. I am a Data Engineer who writes about everything related to Data Science and Interview Preparation for SDE.