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