Inserting at a specific point in a linked list
I am new to programming and I can开发者_运维技巧not figure out how to insert a node at a specific location in a linked list. It has to be inserted at position 3. Help with the logic for the insert would be greatly appreciated.
public void ins (Player p)
{
PlayerNode current = head;
PlayerNode previous = head;
PlayerNode pn = new PlayerNode (new Player (p));
int count=0;
if (isEmpty())
{
pn.setNext(head);
head = pn;
++numberOfItems;
}
else
{
if (count != 3)
{
current = current.getNext();
previous.setNext(pn);
pn.setNext(current);
++count;
}
}
}
Why not use builtins?
add(int index, E element)
Node InsertNth(Node head, int data, int position) {
Node node = head;
if (position == 0){
node = new Node();
node.data = data;
node.next = head;
return node;
}
else {
while(--position > 0){
node = node.next;
}
Node i = node.next;
node.next = new Node();
node.next.data = data;
node.next.next = i;
return head;
}
}
精彩评论