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

Powered by Blogger.

Friday, September 1, 2017

Insert at specified position in LL


Explanation :

Go to position -1 and insert node .
set next and previous pointer for this node.

Note:
Position starts from 0.

Code:

  public static Node InsertNth(Node head, int data, int position)
    {
        Node prev=null;
        Node root=head;
        while(head!=null && position-->0)
        {
            prev=head;
            head=head.Next;
            
        }
        Node n=new Node();
        n.Data=data;
        if(prev!=null)
            prev.Next=n;
        if(prev==null)
            root=n;
        n.Next=head;
        return root;
    }

0 Comments:

Post a Comment

Stats