Sunday, August 24, 2025

LINKED LIST

#include <iostream> using namespace std; struct node { int data; node* next; }; node* head = NULL; int nodeCount = 0; // Current number of nodes const int MAX_NODES = 10; // Maximum allowed nodes void insertAtbeginning(int value) { if (nodeCount >= MAX_NODES) { cout << "Maximum nodes reached!" << endl; return; } node* NEW = new node(); NEW->data = value; NEW->next = head; head = NEW; nodeCount++; cout << " node number is " << nodeCount << endl; } void insert(int value, int position) { if (nodeCount >= MAX_NODES) { cout << "Maximum nodes reached!" << endl; return; } if (position < 1) { cout << "Invalid position!" << endl; return; } if (position == 1) { insertAtbeginning(value); return; } node* NEW = new node(); NEW->data = value; node* temp = head; for (int i = 1; temp != NULL && i < position - 1; i++) { temp = temp->next; } if (temp == NULL) { cout << "Position out of range!" << endl; delete NEW; return; } NEW->next = temp->next; // Correct linking temp->next = NEW; nodeCount++; cout << " node number is " << nodeCount << endl; } void insertAtend(int value) { if (nodeCount >= MAX_NODES) { cout << "Maximum nodes reached!" << endl; return; } node* NEW = new node(); NEW->data = value; NEW->next = NULL; if (head == NULL) { head = NEW; nodeCount++; cout << " node number is " << nodeCount << endl; return; } node* temp = head; while (temp->next != NULL) { // go till last node temp = temp->next; } temp->next = NEW; nodeCount++; cout << " node number is " << nodeCount << endl; }
void display() { node* temp = head; while (temp != NULL) { cout << temp->data << "->"; temp = temp->next; } cout << "NULL" << endl; }
void Del(int position){
if(head==NULL){
    cout<<" list is empty "<<endl;
    return;
}
node*temp=head;
if(position==1){
    head=head->next;
    delete temp;
    return;
}
if(position<1){
    cout<<" invalid position "<<endl;
    return;
}
node*prev=NULL;
for(int i=1;temp!=NULL && i<position;i++){
    prev=temp;
    temp=temp->next;
}
prev->next=temp->next;
delete temp;
}
int main() { insertAtbeginning(5); insertAtend(1); insert(10, 2); insertAtend(15); display(); return 0; }

No comments:

Post a Comment

list in c#

  using System ; using System . Collections . Generic ; class Program {     static void Main () {         // Write your C# code here  ...