on
thecodecandy
- Get link
- X
- Other Apps
// Complete the insertNodeAtPosition function below.
static SinglyLinkedListNode insertNodeAtPosition(SinglyLinkedListNode head, int data, int position) {
SinglyLinkedListNode addNode = new SinglyLinkedListNode(data);
SinglyLinkedListNode temp,temp1,temp2;
int size = 0;
temp2 = head;
while(temp2 != null) {
size++;
temp2 = temp2.next;
}
if (position > 0 && position < size+1) {
if(head == null) {
head = addNode;
}
else {
temp = head;
for(int i = 0; i < position-1; i++) {
temp = temp.next;
}
temp1 = temp.next;
temp.next = addNode;
addNode.next = temp1;
}
}
return head;
}
Comments
Post a Comment