Skip to content

Instantly share code, notes, and snippets.

@LizardLeliel
Last active August 29, 2015 14:08
Show Gist options
  • Save LizardLeliel/d11f12f019934e5e40d1 to your computer and use it in GitHub Desktop.
Save LizardLeliel/d11f12f019934e5e40d1 to your computer and use it in GitHub Desktop.
Dynamic Linked List
#include <iostream>
using namespace std;
int main(int argc, char* argv[]) {
// Node struct
struct Node {
int data;
Node *next;
};
// List depth initialization
cout << "Please type how many nodes you want: ";
int listDepth; cin >> listDepth;
// Initialize nodes (One for filling data, and one for reading)
Node* DynamicLinkedList = new Node;
Node* tracker = DynamicLinkedList;
// Fill data on each node in the list
for (int i = 0; i < listDepth; ++i) {
cout << "This is node #" << i+1 << " please input its data: ";
cin >> tracker->data;
tracker->next = new Node;
tracker = tracker->next;
}
// Set the last node's "next" to null
tracker->next = NULL;
// Read through the list, printing out the data
while (DynamicLinkedList->next != NULL) {
cout << DynamicLinkedList->data << ' ';
DynamicLinkedList = DynamicLinkedList->next;
}
cout << endl;
cin.ignore();
//Todo: delete
//I'm 100% aware of memory leaks. Although due to so many examples not having them
//in the main function, I assumed it wasn't necessary for main().
//I've been recommended otherwise, so I'll get there
return 0;
}
/* Example program:
* Please type how many nodes you want: 4
* This is node #1 please input its data: 33
* This is node #2 please input its data: 98
* This is node #3 please input its data: 9003
* This is node #4 please input its data: 404
* 33 98 9003 494
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment