Delete the node at a given position in a linked list and return a reference to the head node. The head is at position 0. The list may be empty after you delete the node. In that case, return a null value.
Example
llist = 0 → 1 → 2 → 3
position = 2
After removing the node at position 2, llist' = 0 → 1 → 3.
Function Description
Complete the deleteNode function in the editor below.
deleteNode has the following parameters:
Returns
SinglyLinkedListNode pointer: a reference to the head of the modified list
Input Format
The first line of input contains an integer n, the number of elements in the linked list.
Each of the next n lines contains an integer, the node data values in order.
The last line contains an integer, position, the position of the node to delete.
Constraints
1 ≤ n ≤ 1000
1 ≤ list[i] ≤ 1000, where list[i] is the iᵗʰ element of the linked list.
Sample Input
8
20
6
2
19
7
4
15
9
3
Sample Output
20 6 2 7 4 15 9
public static SinglyLinkedListNode deleteNode(SinglyLinkedListNode llist, int position) {
// Write your code here
SinglyLinkedListNode beforeHeadNode = llist;
for(int i = 0; i < position - 1; i++) {
llist = llist.next;
}
if(llist.next.next == null) {
llist.next = null;
return beforeHeadNode;
}
if(position == 0) {
return llist.next;
}
SinglyLinkedListNode afterNode = llist.next.next;
llist.next = afterNode;
return beforeHeadNode;
}
로직