===========================
LINKED LIST — PAGE 1
===========================
Node Structure:
struct ListNode {
int value;
ListNode* next;
};
1. Count Nodes:
int countNodes(ListNode* head){
int c=0; while(head){c++; head=head->next;} return c;
}
2. Display List:
void displayList(ListNode* h){
while(h){ cout<<h->value<<endl; h=h->next; }
}
3. Append:
void appendNode(ListNode*& head,int num){
ListNode* n=new ListNode{num,nullptr};
if(!head) head=n;
else{
ListNode* p=head;
while(p->next) p=p->next;
p->next=n;
}
}
4. Insert at Beginning:
void insertAtBeginning(ListNode*& h,int num){
h=new ListNode{num,h};
}
5. Insert Sorted:
void insertSorted(ListNode*& h,int num){
ListNode* n=new ListNode{num,nullptr};
ListNode* p=h; ListNode* prev=nullptr;
while(p && p->value<num){ prev=p; p=p->next; }
if(!prev){ n->next=h; h=n; }
else{ prev->next=n; n->next=p; }
}
6. Delete First:
void deleteFirst(ListNode*& h){
if(!h) return;
ListNode* t=h; h=h->next; delete t;
}
===========================
LINKED LIST — PAGE 2
===========================
7. Delete Specific Value:
void deleteValue(ListNode*& h,int num){
if(!h) return;
if(h->value==num){ deleteFirst(h); return; }
ListNode* p=h; ListNode* prev=nullptr;
while(p && p->value!=num){ prev=p; p=p->next; }
if(p){ prev->next=p->next; delete p; }
}
8. Delete Last:
void deleteLast(ListNode*& h){
if(!h) return;
if(!h->next){ delete h; h=nullptr; return; }
ListNode* p=h; ListNode* prev=nullptr;
while(p->next){ prev=p; p=p->next; }
prev->next=nullptr; delete p;
}
9. Reverse List:
ListNode* reverseList(ListNode* h){
ListNode* prev=nullptr; ListNode* cur=h; ListNode* nxt;
while(cur){
nxt=cur->next;
cur->next=prev;
prev=cur;
cur=nxt;
}
return prev;
}
10. Destroy Entire List:
void destroyList(ListNode*& h){
ListNode* p=h; ListNode* nxt;
while(p){
nxt=p->next;
delete p;
p=nxt;
}
h=nullptr;
}
11. Find Middle:
ListNode* findMiddle(ListNode* h){
ListNode* s=h; ListNode* f=h;
while(f && f->next){
s=s->next;
f=f->next->next;
}
return s;
}
12. Search Value:
bool searchValue(ListNode* h,int num){
while(h){ if(h->value==num) return true; h=h->next; }
return false;
}