class ReverseLink1{
Node head;
class Node{
int data;
Node next;
public Node(int data){
this.data=data;
this.next=null;
}
@Override
public String toString() {
return "{"+this.data +"}";
}
}
public void push(int data){
Node node=new Node(data);
if(head==null){
head=node;
}else{
Node current=head;
while(current.next!=null){
current=current.next;
}
current.next=node;
}
}
public void display(Node head){
if(head == null){
System.out.println("No data");
}else{
Node current=head;
while(current!=null){
System.out.print(current);
current=current.next;
}
System.out.println("");
}
}
public Node revers(Node head, int k){
if(head == null||head.next == null||k == 0) return head;
//calculating length
Node temp = head;
int length = 1;
while(temp.next != null) {
++length;
temp = temp.next;
}
System.out.println("Length " +length);
//link last node to first node
temp.next = head;
k = k%length; //when k is more than length of list
int end = length-k; //to get end of the list
while(end--!=0) temp = temp.next;
//breaking last node link and pointing to NULL
head = temp.next;
temp.next = null;
return head;
}
}
public class ReverseLinkList1 {
public static void main(String[] args) {
ReverseLink1 reverseLink1=new ReverseLink1();
reverseLink1.push(1);
reverseLink1.push(2);
reverseLink1.push(3);
reverseLink1.push(4);
reverseLink1.push(5);
reverseLink1.push(6);
reverseLink1.push(7);
reverseLink1.display( reverseLink1.head);
ReverseLink1.Node revers = reverseLink1.revers(reverseLink1.head, 3);
reverseLink1.display(revers);
}
}
TechInsiderStory is place where you can find basic knowledge of various technology and framework. TechInsiderStory is provide free knowledge on various technology and framework.
LinkList Rotate ClockWise
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment