//
// main.cpp
// Linked List
//
// Created by Himanshu on 12/09/21.
//
#include <iostream>
using namespace std;
struct node {
int info = 0;
struct node *next;
};
typedef struct node Node;
node* newNode(int data)
{
node* Node = new node();
Node->info = data;
Node->next = NULL;
return(Node);
}
void printLinkedList (Node* head) {
Node *x = head;
while (x != NULL) {
cout<<(x->info)<<" ";
x = x->next;
}
cout<<endl;
}
Node* insertNode (Node *head, Node* x) {
x->next = head;
head = x;
return head;
}
Node* searchNode (Node *head, int k) {
Node* x = head;
while (x != NULL && x->info != k) {
x = x->next;
}
if (x != NULL && x->info == k) {
return x;
} else {
return NULL;
}
}
Node* insertAtPosition (Node *head, Node* x, int k) {
Node* node = head;
while (node != NULL && node->info != k) {
node = node->next;
}
if (node != NULL) {
x->next = node->next;
node->next = x;
}
return head;
}
Node* deleteNode (Node *head, int k) {
Node* x = head, *prev = NULL;
if (x != NULL && x->info == k) {
head = x->next;
//To prevent Memory Leak
delete (x);
return head;
}
while (x != NULL && x->info != k) {
prev = x;
x = x->next;
}
// Deleting a node, requires the node
// previous to the node to be deleted.
if (x != NULL) {
prev->next = x->next;
//To prevent Memory Leak
delete (x);
}
return head;
}
int main() {
Node *head = newNode(5);
head = insertNode (head, newNode(4));
head = insertNode (head, newNode(3));
head = insertNode (head, newNode(2));
head = insertNode (head, newNode(1));
cout<<"Linked List:"<<endl;
printLinkedList(head);
cout<<"Searching Node 3"<<endl;
if (searchNode(head, 3)) {
cout<<"Node 3 is present"<<endl;
}
cout<<"Searching Node 6 "<<endl;
if (!searchNode(head, 6)) {
cout<<"Node 6 is not present"<<endl;
}
cout<<"Inserting Node 6 after 5 "<<endl;
head = insertAtPosition(head, newNode(6), 5);
cout<<"Linked List:"<<endl;
printLinkedList(head);
cout<<"Deleting Node 1"<<endl;
head = deleteNode(head, 1);
cout<<"Linked List:"<<endl;
printLinkedList(head);
cout<<"Deleting Node 6"<<endl;
head = deleteNode(head, 6);
cout<<"Linked List:"<<endl;
printLinkedList(head);
return 0;
}