Monday, October 3, 2011

Singly Linked List

example:
#include <iostream>

using namespace std;

class Node {
private:
Node(string s, Node* n);
string body;
Node* next;
friend class SinglyLinkedList;
};

Node::Node(string s, Node* n){
body = s;
next = n;
};

class SinglyLinkedList{
public:
SinglyLinkedList();
~SinglyLinkedList();
void AddInFront(string s);
void RemoveInFront();
void ShowAll();
private:
Node* head;
};

SinglyLinkedList::SinglyLinkedList(){
head = NULL;
};

SinglyLinkedList::~SinglyLinkedList(){
while (head != NULL){
RemoveInFront();
}
};

void SinglyLinkedList::AddInFront(string s){
Node* n = new Node(s, head);
head = n;
};

void SinglyLinkedList::RemoveInFront(){
if(head != NULL){
Node* tmp = head;
head = head->next;
delete tmp;
}
};

void SinglyLinkedList::ShowAll(){
Node* n = head;
while(n != NULL){
cout << n -> body << endl;
n = n -> next;
}
}

int main()
{
cout << "- Singly Linked List exercise -" << endl;

cout << "Create a new SinglyLinkedList: " << endl;
SinglyLinkedList mySinglyLinkedList;
mySinglyLinkedList.ShowAll();
cout << endl;

cout << "Remove nothing in a empty Singly Linked List: " << endl;
mySinglyLinkedList.RemoveInFront();
mySinglyLinkedList.ShowAll();
cout << endl;

cout << "Insert something: " << endl;
mySinglyLinkedList.AddInFront("ABC");
mySinglyLinkedList.AddInFront("DEFGH");
mySinglyLinkedList.AddInFront("I");
mySinglyLinkedList.AddInFront("JK");
mySinglyLinkedList.AddInFront("LMN");
mySinglyLinkedList.ShowAll();
cout << endl;

cout << "Remove something: " << endl;
mySinglyLinkedList.RemoveInFront();
mySinglyLinkedList.RemoveInFront();
mySinglyLinkedList.ShowAll();
cout << endl;

return 0;
}


Singly Linked List



No comments:

Post a Comment