-
Notifications
You must be signed in to change notification settings - Fork 0
linked list c
stachulemko edited this page Oct 13, 2024
·
1 revision
#include <iostream>
using namespace std;
// Structure for a node in the linked list
struct Node {
int data;
Node* next;
};
// Define the linked list class
class LinkedList {
// Pointer to the first node in the list
Node* head;
int size;
public:
LinkedList(){
head=NULL;
size=0;
}
void insert_at_begining(int value){
Node* new_node;
new_node=new Node;
new_node->data=value;
new_node->next=head;
head=new_node;
size++;
}
void insert_at_the_end(int value){
Node* new_node;
new_node=new Node;
new_node->data=value;
if(head==NULL){
head=new_node;
}
else{
Node* current_node=head;
while(current_node->next!=NULL){
current_node=current_node->next;
}
current_node->next=new_node;
}
size++;
}
void insert_at_position(int value ,int position){
int current_position_num=0;
Node* new_node;
new_node=new Node;
new_node->data=value;
Node* current_node=head;
while(current_node->next!=NULL and current_position_num > position-1){
current_position_num++;
current_node=current_node->next;
}
new_node->next=current_node->next;
current_node->next=new_node;
}
void
void display() {
if (!head) {
cout << "List is empty." << endl;
return;
}
Node* temp = head;
while (temp) {
cout << temp->data << " -> ";
temp = temp->next;
}
cout << "NULL" << endl;
}
};
int main()
{
LinkedList l;
l.insert_at_begining(10);
l.insert_at_begining(5);
l.insert_at_the_end(4);
l.insert_at_position(3,1);
l.display();
return 0;
}