Java program to reverse the link in
single link list.
Answers
Java program to reverse the link in single link list
Explanation:
Java program
public class Main{
//head object of class node will point to the
//head of the linked list
Node head;
//class node to create a node with data and
//next node (pointing to node)
public static class Node{
int data;
Node next;
Node(int data,Node next){
this.data=data;
this.next=next;
}
}
public static void main (String[] args){
//Main object ll
Main ll=new Main();
//Six nodes will be created dynamically
Node first=new Node(11,null);
Node second=new Node(72,null);
Node third=new Node(13,null);
Node fourth=new Node(84,null);
Node fifth=new Node(45,null);
Node sixth=new Node(10,null);
ll.head=first;
first.next=second;
second.next=third;
third.next=fourth;
fourth.next=fifth;
fifth.next=sixth;
ll.printlist();
ll.reverselist();
ll.printlist();
}
//this function will print the list
public void printlist() {
Node n= head;
//loop continues until it points to null
while(n!=null){
System.out.print(n.data+" ");
n=n.next;
}
System.out.println();
}
//this function will reverse the list
//by changing current node to previous
public void reverselist() {
Node current=head;
Node prev=null;
Node nextnode=null;
//for first node previous node will be null
while(current!=null){
//reverse the link by assigning current.nextnode
//to previous node and move current node and
//previous node by 1
nextnode=current.next;
current.next=prev;
prev=current;
current=nextnode;
}
//head of the list is assigned as prevous node
//which will contain the last node
head=prev;
}
}
Output
11 72 13 84 45 10
10 45 84 13 72 11