JAVA this function reverses the linked list Examples thi
JAVA
/**
* this function reverses the linked list
*
* Examples: this : null ==> resulting this : null this : 2 --> null ==>
* resulting this : 2 --> null this : -5 --> 5 --> -4 --> null ==> resulting
* this : -4 --> 5 --> -5 --> null this : 1 --> 3 --> 5 --> null ==>
* resulting this : 5 --> 3 --> 1 --> null
*/
Function name:
public void reverse() {
// TODO
Solution
 package reversealinkedlist;
import java.io.*;
/**
 *
 * @author Ramesh
 */
 public class ReverseALinkedList{
//This class represents the Node
 static class Node{
 int x;
 Node link;
 Node(int x){
 this.x = x;
 link = null;
 }
 }
   
 static public void reverse(){
 //Start from the head node
 Node present = head;
 Node prev = null;
 //Iterate through all the elements in the list
 while(present!=null){
 //Store the next element in this variable
 Node next = present.link;
 //Changing the ilnk of the present node to the previously visited node
 present.link = prev;
 //Changing the previous node to the present node
 prev = present;
 //Moving to the next node by chaning the present
 present = next;
 }
 head = prev;
 }
 static Node head;
 public static void main(String[] args) throws IOException{
 head = new Node(1);
 Node a = new Node(2);
 head.link = a;
 Node b = new Node(3);
 a.link = b;
 Node c = new Node(4);
 b.link = c;
 //EG ;: 1 -- > 2 -- > 3 -- > 4
 reverse();
 Node t = head;
 while(t!=null){
 System.out.println(t.x);
 t = t.link;
 }
 }
 }


