Instagram
youtube
Facebook
Twitter

Delete a node| Linked List

Task (easy)

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:
SinglyLinkedListNode pointer llist: a reference to the head node in the list
int position: the position of the node to remove

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 ith 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

Solution 1

def deleteNode(llist, position):

    if position == 0:

        return llist.next

    node = llist

    for _ in range(position - 1):

        node = node.next

    node.next = node.next.next

    return llist

Solution 2

def deleteNode(llist, position):

    if position == 0:

        return llist.next

    i = 0

    cur = llist

    while cur:

        if position-1 == i:

            break

        i+=1

        cur = cur.next   

    cur.next = cur.next.next

    return llist

Explanation Steps

1.Check if the list is empty.

2. Handle deletion of the head node.

3.Traverse the list to find the node to delete.

4. Update pointers to remove the node from the list.