Like arrays, Linked List is a linear data structure. Unlike arrays, linked list elements are not stored at a contiguous location; the elements are linked using pointers.
struct node{
int data;
node* next;
node(int val){
data = val;
next = NULL;
}
};
void insertEl(node* &head, int val){
node * newNode = new node(val);
if (head == NULL)
{
head = newNode;
return;
}
node* temp = head;
while (temp->next != NULL)
{
temp = temp->next;
}
temp->next = newNode;
}
void display(node* head){
node * temp = head;
while(temp != NULL){
cout<<temp->data<<"->";
temp = temp->next;
}
cout<<"NULL"<<endl;
}
void deleteKey(node * &head, int key){
node * temp = head;
node * prev =NULL, * next = NULL;
if(temp != NULL && temp->data == key){
head = temp->next;
free(temp);
return;
}
while(temp != NULL && temp->data != key){
next = temp->next;
prev = temp;
temp = next;
}
if(temp == NULL){
cout<<"Key not found"<<endl;
return;
}
next = temp->next;
prev->next = next;
free(temp);
}
0 Comments