Skip to content

Instantly share code, notes, and snippets.

@bzdgn
Last active November 1, 2015 00:23
Show Gist options
  • Save bzdgn/26d1f5d672d630436fa8 to your computer and use it in GitHub Desktop.
Save bzdgn/26d1f5d672d630436fa8 to your computer and use it in GitHub Desktop.
Linked List Sample in C++
#include <iostream>
#include <string>
using namespace std;
class Employee
{
private:
friend class EmployeeList;
string name;
int age;
int yearOfWork;
Employee *next;
public:
Employee(const string &, int, int);
void print() const;
const string& getName() const { return name; }
~Employee() { cout << "Destructor of Employee" << endl; }
};
Employee::Employee(const string &newName, int a, int workYear)
{
name = newName;
age = a;
yearOfWork = workYear;
next = 0;
}
void Employee::print() const
{
cout << "Name: " << name << ", Age: " << age << ", Year Of Work: " << yearOfWork << endl;
}
class EmployeeList
{
private:
Employee *head;
public:
EmployeeList() { head = 0; };
bool append(const string &, int, int);
bool del(const string &);
void print() const;
~EmployeeList();
};
bool EmployeeList::append(const string &n, int a, int workYear)
{
Employee *previous, *current, *newEmployee;
newEmployee = new Employee(n, a, workYear);
if (!newEmployee)
return false;
if (head)
{
previous = head;
current = head->next;
while (current)
{
previous = current;
current = current->next;
}
previous->next = newEmployee;
} else {
head = newEmployee;
}
return true;
}
bool EmployeeList::del(const string &n)
{
Employee *previous, *current;
if (head)
{
if (n == head->getName())
{
previous = head;
head = head->next;
delete previous;
return true;
}
previous = head;
current = head->next;
while ( current && ( n != current->getName() ) )
{
previous = current;
current = current->next;
}
if (current == 0)
return false;
previous->next = current->next;
delete current;
return true;
}
else {
return false;
}
}
void EmployeeList::print() const
{
Employee *tempPtr;
if (head)
{
tempPtr = head;
while (tempPtr)
{
tempPtr->print();
tempPtr = tempPtr->next;
}
}
else {
cout << "The list is empty" << endl;
}
}
EmployeeList::~EmployeeList()
{
Employee *temp;
while (head)
{
temp = head;
head = head->next;
delete temp;
}
}
int main()
{
EmployeeList list;
list.print();
list.append("Employee 1", 25, 1);
list.append("Employee 2", 32, 4);
list.append("Employee 3", 31, 5);
list.print();
if (!list.del("Employee 6"))
cout << "Employee x not found" << endl;
if (!list.del("Employee 2"))
cout << "Employee 2 not found" << endl;
list.print();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment