Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Monday, May 14, 2018

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;
    }

0 Comments:

Post a Comment

Stats