#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; | |
// Move back to beginning | |
tracker = DynamicLinkedList; | |
// Read through the list, printing out the data | |
while (tracker->next != NULL) { | |
cout << tracker->data << ' '; | |
tracker = tracker->next; | |
} | |
cout << endl; | |
cin.ignore(); | |
// Start cleanup | |
tracker = DynamicLinkedList; | |
while (tracker != NULL) | |
{ | |
// Store the next node | |
Node* next = tracker->next; | |
// Remove the current one | |
delete tracker; | |
// Step to the next one | |
tracker = next; | |
} | |
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