# Delete a node under given conditions

## In the given linked list write a function to delete a given node. Under conditions :

a) Parameter of function are pointer to the start node and node to be deleted.

b) Should not accept pointer to head node, should not return pointer to head node.(Linked list never become empty)

## Algorithm

There are two possibilities either we need to delete head node or we need to delete any other node.

a. When we are deleting node other than head node, we delete normally by keeping track of previous node and changing next of previous node.

b. If we want to delete head node, we cannot just change the pointer of head to head->next.

c. We should copy data of next node to head, change the next of head and remove the link of next node.

d. Delete next to head.

## C++ Program

```#include <bits/stdc++.h>

using namespace std;

struct LLNode
{
int data;
struct LLNode *next;
};

void DeleteNode(struct LLNode *head, struct LLNode *nodeToBeDeleted)
{
//Node to be deleted is start node
{
//only single node
{
cout<<"list can`t be empty"<<endl;
return;
}
//code data of next node to head
//delete next
free(nodeToBeDeleted);
return;
}
//Delete node other than head
//use normal deletion method
struct LLNode *prev = head;
while(prev->next != NULL && prev->next != nodeToBeDeleted)
{
prev = prev->next;
}
if(prev->next == NULL)
{
cout<<"Invalid input!"<<endl;
return;
}
prev->next = prev->next->next;
free(nodeToBeDeleted);
return;
}
/* Function to insertAtBeginning a node */
void insertAtBeginning(struct LLNode** head, int dataToBeInserted)
{
struct LLNode* curr = new LLNode;
curr->data = dataToBeInserted;
curr->next = NULL;
*head=curr; //if this is first node make this as head of list

else
{
curr->next=*head; //else make the curr (new) node's next point to head and make this new node a the head
}

//O(1) constant time
}

void display(struct LLNode**node)
{
struct LLNode *temp= *node;
while(temp!=NULL)
{
if(temp->next!=NULL)
cout<<temp->data<<"->";
else
cout<<temp->data;

temp=temp->next; //move to next node
}
//O(number of nodes)
cout<<endl;
}

//Main function
int main()
{
struct LLNode *head = NULL;

cout<<"Input linked List: ";
cout<<"a)"<<endl;

cout<<"\nOutput linked list: ";
cout<<endl;
cout<<"b)"<<endl;
/* Let us delete the the first node */