Rotate Linkedlist by K
Problem:
if the given linked list is 10->20->30->40->50->60 and k is 4, the list should be modified to
50->60->10->20->30->40.
idea is to find position from where we need to break the link i.e. when k=0
make next node of last element to start
make next node of kth node to null
Code:
public void rotate(Node head,int k)
{
Node cur=head;
Node prev=cur;
Node res=null;
while(cur!=null)
{
--k;
if(k==0)
{ res=cur;
//System.out.print(cur.data+" ");
}
prev=cur;
cur=cur.next;
}
prev.next=head;
head=res.next;
res.next=null;
while(head!=null)
{System.out.print(head.data+" ");
head=head.next;
}
}
if the given linked list is 10->20->30->40->50->60 and k is 4, the list should be modified to
50->60->10->20->30->40.
idea is to find position from where we need to break the link i.e. when k=0
make next node of last element to start
make next node of kth node to null
Code:
public void rotate(Node head,int k)
{
Node cur=head;
Node prev=cur;
Node res=null;
while(cur!=null)
{
--k;
if(k==0)
{ res=cur;
//System.out.print(cur.data+" ");
}
prev=cur;
cur=cur.next;
}
prev.next=head;
head=res.next;
res.next=null;
while(head!=null)
{System.out.print(head.data+" ");
head=head.next;
}
}
0 Comments:
Post a Comment