Move all zero to front of linkedlist
Idea is look for node with value 0
Then delete link from there and add it to start
Code:
public Node moveZeroes(Node head){
Node cur=head;
Node prev=null;
boolean flag=false;
while(cur!=null && cur.next!=null)
{
flag=false;
if(cur.next.data==0)
{
Node temp=cur.next;
cur.next=cur.next.next;
temp.next=head;
head=temp;
flag=true;
}
prev=cur;
if(!flag)
cur=cur.next;
}
if(cur!=null && cur.data==0)
{
prev.next=null;
cur.next=head;
head=cur;
}
return head;
}
Then delete link from there and add it to start
Code:
public Node moveZeroes(Node head){
Node cur=head;
Node prev=null;
boolean flag=false;
while(cur!=null && cur.next!=null)
{
flag=false;
if(cur.next.data==0)
{
Node temp=cur.next;
cur.next=cur.next.next;
temp.next=head;
head=temp;
flag=true;
}
prev=cur;
if(!flag)
cur=cur.next;
}
if(cur!=null && cur.data==0)
{
prev.next=null;
cur.next=head;
head=cur;
}
return head;
}
0 Comments:
Post a Comment