Search code examples
c++algorithmlinked-listsingly-linked-listpseudocode

Delete nth node from both beginning and end of singly linked list


I'm just starting to learn linkedlist.

I can come up with an approach to delete a nth node from the beginning and end separately but I couldn't take care of the checks needed to perform both at the same time.

Delete nth node from both beginning and end

INPUT:

1->2->3->4->5->6->7->8->9->10->NULL
N =4

OUTPUT:

1->2->3->5->6->8->9->10->NULL

DELETE FROM BEGINNING :

void deletePosition(struct Node** head, int n){
struct Node* temp = *head;
struct Node* previous;

int size=0;

while(node!=NULL){
    node = node->next;
    size++;
}

if(n < 1 || n > size){
    return;
}

if(n == 1){
    *head = (*head)->next;
    free(temp);
    return;
}

while (--n) 
{
    previous = temp; 
    temp = temp->next; 
}
previous->next = temp->next;

free(temp);

}

DELETE FROM THE END :

    Node* deleteNode(Node* head, int key)
{
    Node* temp;
    Node* first = head;
    Node* second = head;
    for (int i = 0; i < key; i++) {
        if (second->next == NULL) {
            if (i == key - 1) {
                temp = head;
                head = head->next;
                free(temp);
            }
            return head;
        }
        second = second->next;
    }
 
    while (second->next != NULL) {
        first = first->next;
        second = second->next;
    }
 
    temp = first->next;
    first->next = first->next->next;
    free(temp);
    return head;
}

general algorithm or pseudo code would be much appreciated.


Solution

  • Suppose you are at node 3.

    helper = this -> next -> next;
    delete this -> next;
    this -> next = helper;
    
    

    So basically you need to get to the node after the one you seek to delete prior to that deletion as then there will be no way of accessing it.

    To check if there are any nodes at all:

    if(root == NULL)
    {
     /// there are no nodes
    }
    

    If there are nodes:

    traverse = root;
    int count = 0;
    while(traverse != NULL)
    {
       ++count;
       if(count == n)
       { /* you are at the nth node */ }
       traverse = traverse -> next;
    }
    

    Notice that if you delete node n and you are still at node (n-1), you will just have to do a seperate "shift of indicies," so to say, to remove another node. So if you want to delete another node that was previously the pth one, then just do in the if statement

    
    ///the deletion
    ++count;
    

    Effectively you will get count == p when you arrive at the node that was the pth one until any deletions.