Linked List Implementation Using Cpp
- Home
- Tutorials
- Data Structure And Algorithms
- Data Structure And Algorithms Programs
- Linked List
- Program
#include <iostream>
using namespace std;
struct node {
int data;
node *next;
};
node *head; // head pointer to traverse nodes
void insertAtBeg(int val) {
node *temp = new node(); // allocating memory to node pointer
// (node*)malloc(sizeof(node));
temp->data = val;
temp->next = head;
head = temp;
}
void insertAtEnd(int val) {
node *temp = new node();
// (node*)malloc(sizeof(node));
temp->data = val;
temp->next = NULL;
if(head == NULL) {
head = temp; // first node of link list
} else {
node *ptr = head;
while(ptr->next != NULL) {
ptr = ptr->next;
}
ptr->next = temp;
}
}
void display() { // Method to display nodes
if(head == NULL) {
cout<<"List is Empty!.......";
return;
}
node *temp;
temp = head; // temporarily assigning head to temp node
while(temp != NULL) { // loop until last node of list
cout<<temp->data<<" -> ";
temp = temp->next; // move to next node using pointer
}
cout<<"NULL"<<endl; // after printing value of last node
}
void deleteNode(int val) {
if(head == NULL) {
cout<<"List is Empty!.......";
return;
}
if(head->data == val) {
cout<<"Deleting Head Node!....."<<endl;
node *temp = head;
head = head->next;
delete temp; // returning
return;
}
node *temp;
temp = head;
int flag = 0;
while(temp != NULL) {
if(temp->next->data == val) {
flag = 1;
break;
}
temp = temp->next;
}
if(flag == 1) {
temp->next = temp->next->next;
}
}
void search(int val) {
if(head == NULL) {
cout<<"List is Empty!.......";
return;
}
node *temp = head;
int flag = 0;
int pos = 1;
while(temp != NULL) {
if(temp->data == val) {
flag = 1;
break; // terminate loop if value found
}
temp = temp->next;
pos++; // increment in position variable
}
if(flag == 1) { // check either value found
cout<<"Value is found at "<<pos<<endl;
} else {
cout<<"Value is not found"<<endl;
}
}
int main(int argc, char** argv) {
insertAtBeg(30);
insertAtBeg(23);
insertAtEnd(56);
insertAtEnd(66);
insertAtBeg(90);
insertAtBeg(16);
insertAtBeg(160);
display();
search(90);
return 0;
}
Output