Here is a sample linked list implementation. We should obviously use the std::list that comes with the STL under the header <list>. But since I was not posting something so its just to break the ice and post something...:)
[CODE]
#include<iostream>
struct Node{
int data;
Node* next;
};
void InsertAfter(Node **head, int value){
if(*head==NULL){
Node* temp=NULL;
temp = new Node;
temp->data = value;
temp->next = NULL;
*head = temp;
}else{
Node *temp = new Node;
temp->data = value;
temp->next = (*head)->next;
(*head)->next = temp;
}
}
void DeleteAfter(Node **head){
if(*head==NULL){
return;
}else{
Node *temp = NULL;
temp = (*head)->next;
(*head)->next = (*head)->next->next;
delete temp;
temp=NULL;
}
}
int DeleteAll(Node **head,int value){
int count=0;
Node *p = NULL;
Node *q = (*head);
if(*head==NULL){
count =0;
}else{
while((q)!=NULL){
if((q)->data==value){
Node *temp = NULL;
temp = q;
if ( p!=NULL){
p->next = q->next;
}else{
(*head) = q->next;
}
q = q->next;
delete temp;
temp = NULL;
++count;
}else{
p = q;
q = q->next;
}
}
}
return count;
}
void DisplayList(Node *head){
if(head!=NULL){
std::cout << head->data << "\n";
while(head->next!=NULL){
std::cout <<
head->data << "\n";
head =
head->next;
}
}
std::cout << "\n\n";
}
int main(){
Node *head=NULL;
InsertAfter(&head,10);
InsertAfter(&head,10);
InsertAfter(&head,20);
InsertAfter(&head,10);
DisplayList(head);
DeleteAfter(&head);
DisplayList(head);
int a = DeleteAll(&head,10);
std::cout << "Number Of Nodes deleted
having value 10 = " <<
a <<"\n\n";
DisplayList(head);
return 0;
}
Saturday, October 22, 2005
Subscribe to:
Post Comments (Atom)
2 comments:
Your function DisplayList doesn't
return the second entry in the list.
Just replace
while(head->next!=NULL) with
while(head != NULL)
in the DisplayList function.
Thanks for the code m8.
this list not maintaining order, too bad
Post a Comment