Created
November 3, 2015 11:42
-
-
Save toboqus/02fae8b36a86ab7e8299 to your computer and use it in GitHub Desktop.
Linked List in C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* linkedList.cpp | |
* | |
* Created on: 3 Nov 2015 | |
* Author: Alex | |
*/ | |
#include <iostream> | |
#include "linkedList.hpp" | |
using namespace std; | |
linkedList::linkedList(){ | |
root = NULL; | |
} | |
linkedList::~linkedList(){ | |
destroyList(root); | |
} | |
void linkedList::add(int val){ | |
if(root == NULL){ | |
root = new node; | |
root->val = val; | |
root->next = NULL; | |
}else{ | |
add(root, val); | |
} | |
} | |
void linkedList::add(node *root, int val){ | |
if(root->next == NULL){ | |
root->next = new node; | |
root->next->val = val; | |
root->next->next = NULL; | |
}else{ | |
add(root->next, val); | |
} | |
} | |
void linkedList::destroyList(node *root){ | |
if(root != NULL){ | |
destroyList(root->next); | |
delete root; | |
} | |
} | |
void linkedList::printList(){ | |
printList(root); | |
} | |
void linkedList::printList(node *root){ | |
node *pointer = root; | |
while(pointer != NULL){ | |
cout<<pointer->val << ","; | |
pointer = pointer->next; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* linkedList.hpp | |
* | |
* Created on: 3 Nov 2015 | |
* Author: Alex | |
*/ | |
#ifndef LINKEDLIST_HPP_ | |
#define LINKEDLIST_HPP_ | |
struct node{ | |
int val; | |
node *next; | |
}; | |
class linkedList { | |
public: | |
linkedList(); | |
~linkedList(); | |
void add(int val); | |
void printList(); | |
private: | |
node *root; | |
void add(node *root, int val); | |
void destroyList(node *root); | |
void printList(node *root); | |
}; | |
#endif /* LINKEDLIST_HPP_ */ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include "linkedList.hpp" | |
using namespace std; | |
int main(){ | |
linkedList list; | |
list.add(1); | |
list.add(2); | |
list.add(3); | |
list.add(4); | |
list.add(5); | |
list.add(6); | |
list.add(7); | |
list.add(8); | |
list.add(9); | |
list.add(10); | |
list.printList(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment