Skip to content

Instantly share code, notes, and snippets.

@yeukhon
Created January 13, 2013 01:08
Show Gist options
  • Save yeukhon/4521540 to your computer and use it in GitHub Desktop.
Save yeukhon/4521540 to your computer and use it in GitHub Desktop.
Simple List implementation in C++. Just my first attempt. So far only works for int. That's fine ...
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode ()
{
this->val = 0;
this->next = 0;
}
ListNode (int *newval)
{
this->val = *newval;
this->next = 0;
}
};
struct List {
List()
{
this->startNode = 0;
this->endNode = 0;
this->size = 0;
}
~List()
{
// there is at least one item
if(startNode != 0)
{
// release memory starting from the second item
ListNode *current, *soon;
current = this->startNode->next;
while(current != 0) // if there are at least two items
{
/* When there is no more items after current,
* delete current and leave.
* Otherwise, free up current and move on to
* the next item.
*/
if(current->next != 0)
{
soon = current->next;
delete current;
current = soon;
}
else
{
delete current;
break;
}
}
}
delete this->startNode;
delete this->endNode;
}
/* Input: pointer of the item
* Output: Appends the item to the end of the list
* With the help of endNode, we can efficently appends
* the item to the end of the list.
*/
void add(int *val)
{
this->size += 1;
ListNode *newNode = new ListNode(val);
if (this->size == 1)
{
this->startNode = newNode;
this->endNode = newNode;
}
else
{
this->endNode->next = newNode;
this->endNode = newNode;
}
/*
if (this->size == 1)
{
this->startNode = newNode;
}
else
{
ListNode *tmp = this->startNode;
while (tmp->next)
tmp = tmp->next;
tmp->next = newNode;
}
*/
}
int get_size()
{
return this->size;
}
void print_all()
{
ListNode *tmp = this->startNode;
for(size_t i = 1; i <= this->size; ++i)
{
cout << "item #" << i << " : val = " << tmp->val << endl;
tmp = tmp->next;
}
}
private:
ListNode *startNode;
ListNode *endNode;
size_t size;
};
int main()
{
int *item, val = 1;
item = &val;
List myList = List();
for (; val <= 10; ++val)
{
item = &val;
myList.add(item);
}
cout << myList.get_size() << endl;
cout << endl;
myList.print_all();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment