Skip to content

Instantly share code, notes, and snippets.

@Menginventor
Last active July 1, 2017 12:07
Show Gist options
  • Save Menginventor/c4b025cee44a8327cdca3eefd1c84faf to your computer and use it in GitHub Desktop.
Save Menginventor/c4b025cee44a8327cdca3eefd1c84faf to your computer and use it in GitHub Desktop.
C++ linked list example (base on Arduino environment)
/*
C++ linked list example (base on Arduino environment)
by Dhmadhawach Horesuwan
1/7/2560 , Bangkok , Thailand
*/
class linked_list {
struct node {
char data;// you can change this to datatype which you want.
node* next;
node* previous;
};
public:
unsigned int _length = 0;
node* head = NULL;
node* tail = NULL;
void add(char data_add) {
node* new_node = new node();
new_node->data = data_add;
if (_length == 0) {
head = new_node;
tail = new_node;
}
else {
tail->next = new_node;
new_node -> previous = tail;
tail = new_node;
}
_length++;
}
char remove() {
if (_length > 0) {
char end_data = tail -> data;
node* end = tail;
tail = tail -> previous;
delete end;
_length--;
return end_data;
}
return 0;
}
char pop() {
if (_length > 0) {
char head_data = head -> data;
node* first = head;
head = head -> next;
delete first;
_length--;
return head_data;
}
return 0;
}
void insert(unsigned int index, char data_add) {
node* new_node = new node();
new_node->data = data_add;
if (index >= _length) {
add(data_add);
}
else if(index == 0){
new_node->next = head;
head->previous = new_node;
head = new_node;
_length++;
}
else {
node* crr = head;
for (int i = 0; i < index; i++) {
crr = crr->next;
}
new_node->previous = crr->previous;
new_node->next = crr;
crr->previous->next = new_node;
crr->previous = new_node;
_length++;
}
}
void print() {
node* crr = head;
for (int i = 0; i < _length; i++) {
Serial.println(crr->data);
crr = crr->next;
}
}
};
int freeRam () {
extern int __heap_start, *__brkval;
int v;
return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}
void setup() {
Serial.begin(115200);
Serial.println("available RAM before add = " + String(freeRam()));
linked_list simple;
/*
for (char i = 'A'; i <= 'Z'; i++) {
simple.add(i);
}
Serial.println("data length = " + String(simple._length));
Serial.println("available RAM after add= " + String(freeRam()));
simple.print();
for (char i = 'A'; i <= 'Z'; i++) {
Serial.print(simple.remove()); // print which that remove
//Serial.print(simple.pop());
}
Serial.println();
Serial.println("available RAM after delete all = " + String(freeRam()));
Serial.println("data length = " + String(simple._length));
*/
for (char i = '0'; i <= '9'; i++) {
simple.add(i);
}
simple.insert(10,'X');
simple.print();
}
void loop() {
// put your main code here, to run repeatedly:
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment