Uploaded by Emaan 364

SINGLE LINKLIST BASIC OPERATIONS (1)

advertisement
#include <cstddef>
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node * next;
};
void print_list(Node * temp) {
cout << "\nPrinting new list..." << endl;
while (temp != NULL) {
cout << temp->data << " ";
temp = temp->next;
}
}
void insert_at_begin( Node **
head_ref, int new_data) {
// struct Node * new_node = (struct Node *
) malloc(sizeof(struct Node));
Node*new_node = NULL;
new_node= new Node();
new_node->data = new_data;
new_node->next = ( * head_ref);
( * head_ref) = new_node;
}
void insert_at_end( Node ** head_ref, int
new_data) {
// struct Node * new_node = (struct Node *
) malloc(sizeof(struct Node));
Node*new_node = NULL;
new_node= new Node();
struct Node * last = * head_ref;
new_node->data = new_data;
new_node->next = NULL;
while (last->next != NULL)
last = last->next;
last->next = new_node;
}
void insertAfter( 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));
Node*new_node = NULL;
new_node= new Node();
new_node->data = new_data;
new_node->next = prev_node->next;
prev_node->next = new_node;
}
void delete_at_start( Node**head_ref){
Node*temp=(*head_ref);
// Delete linkedlist from beginiing
(*head_ref)=temp->next;
free(temp);
}
void delete_at_end( Node**head_ref)
{
Node*prev;
Node* temp = (*head_ref);
while(temp->next!=NULL){
prev=temp;
temp = temp->next;
}
prev->next = NULL;
free(temp);
}
void delete_at_middle( Node**head_ref, int
position)
{ int i;
Node*prev;
Node*temp=(*head_ref);
for(int i=1; i< position; i++) {
if(temp->next!=NULL) {
prev=temp;
temp = temp->next;
}
}
prev->next = temp->next;
free(temp);
}
void searchNode( Node** head_ref, int key) {
Node* current = *head_ref;
while (current != NULL) {
if (current->data == key)
cout<<"key is found";
current = current->next;
}
}
int main() {
Node * head = NULL;
Node * second = NULL;
Node * third = NULL;
head = new Node();
second = new Node();
third = new Node();
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = NULL;
print_list(head);
insert_at_begin(&head, 11);
print_list(head);
insert_at_end(&head, 2);
print_list(head);
insertAfter(second, 5);
print_list(head);
insertAfter(second, 44);
print_list(head);
insertAfter(second, 76);
print_list(head);
insertAfter(second, 5);
print_list(head);
insertAfter(second, 32);
print_list(head);
delete_at_start(&head);
print_list(head);
delete_at_end(&head);
print_list(head);
delete_at_middle(&head, 5);
cout<<endl;
print_list(head);
searchNode(&head, 32);
}
Download