#include <stdlib.h>
#include <iostream>
using namespace std;
struct Node {
int data;
struct Node* next;
};
void insert_Beg(struct Node** head_x, int new_data) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_x);
(*head_x) = new_node;
}
void insertAfter(struct Node* prev_node, int new_data) {
if (prev_node == NULL) {
cout << "the given previous node cannot be NULL";
return;
}
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = prev_node->next;
prev_node->next = new_node;
}
void insert_End(struct Node** head_x, int new_data) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
struct Node* last = *head_x;
new_node->data = new_data;
new_node->next = NULL;
if (*head_x == NULL) {
*head_x = new_node;
return;
}
while (last->next != NULL) last = last->next;
last->next = new_node;
return;
}
void deleteNode(struct Node** head_x, int m) {
struct Node *temp = *head_x, *prev;
if (temp != NULL && temp->data == m) {
*head_x = temp->next;
free(temp);
return;
}
while (temp != NULL && temp->data != m) {
prev = temp;
temp = temp->next;
}
if (temp == NULL) return;
prev->next = temp->next;
free(temp);
}
bool searchNode(struct Node** head_x, int m) {
struct Node* current = *head_x;
while (current != NULL) {
if (current->data == m) return true;
current = current->next;
}
return false;
}
void sortLinkedList(struct Node** head_x) {
struct Node *current = *head_x, *index = NULL;
int temp;
if (head_x == NULL) {
return;
} else {
while (current != NULL) {
index = current->next;
while (index != NULL) {
if (current->data > index->data) {
temp = current->data;
current->data = index->data;
index->data = temp;
}
index = index->next;
}
current = current->next;
}
}
}
void displayList(struct Node* node) {
while (node != NULL) {
cout << node->data << " ";
node = node->next;
}
}
int main() {
struct Node* head = NULL;
insert_End(&head, 10);
insert_Beg(&head, 20);
insert_Beg(&head, 30);
insert_End(&head, 40);
displayList(head);
cout<<endl;
insertAfter(head->next, 50);//pointed element is 10
cout << "Current pointing to 10 Node after inserting : "<<endl;
displayList(head);
}
Comments
Leave a comment