Node Delete Node: ( Head, N) ( Current - Node Head

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

Node* Delete(Node *head, int n)

{
Node *current_node = head;

// To Traverse The linked list.

// We keep track of what the previous node is.


Node *previous_node = NULL;
for(int i=0;i<n;i++)

// Traverse to the nth node

{
previous_node = current_node;
current_node = current_node->next;
}

// current_node contains the nth element


// previous_node contains the (n-1)th element.
if(n!=0)

// Update (n-1)th node

previous_node->next = current_node->next;
else

// Update the head node.

head = head->next;
free(current_node);

// Delete the nth node

return head;

// Return the modified linked list.

/*
Insert Node at a given position in a linked list
The linked list will not be empty and position will always be valid
First element in the linked list is at position 0
Node is defined as
struct Node
{
int data;
struct Node *next;
}

*/
Node* InsertNth(Node *head,int data, int position) // n is position from beginning
{
// Node to be inserted in given position
Node *ToBeInserted;

// Allocating Memory
ToBeInserted = new Node;

// Filling the Data to New Node


ToBeInserted -> data = data;
ToBeInserted -> next = NULL;

// It might be our First Node in Linked List


if(head == NULL) {

//Address of New Node Becomes our head


return (head = ToBeInserted);
}

// Node Might to be inserted At Head


else if(position == 0) {
// Joining previous Linked List After new Node
ToBeInserted -> next = head;

// Address of New Node Becomes our head


return (head = ToBeInserted);
}

You might also like