Direct Linked List
/* * This simple program builds a linked list of integers, then prints the * integers out backwards. */ #include <iostream> /* * This class represents one node of the linked list. */ class node { public: // Construct, with data. node(int i, node *n = NULL) { m_data = i; m_next = n; } int data() { return m_data; } node * next() { return m_next; } private: int m_data; node * m_next; }; int main() { // Build the list, adding each new item to the head. node *list = NULL; int n; std::cout << "Enter some ints: "; while(std::cin >> n) { list = new node(n, list); } // Print the contents of the list. This will be reverse of the // input order. std::cout << "Backwards: "; node *scan = list; while(scan != NULL) { std::cout << scan->data() << " "; scan = scan->next(); } // Clean up the list by deleting each node. (Each new needs to // be deleted.) scan = list; while(scan != NULL) { node *zombie = scan; scan = scan->next(); delete zombie; } std::cout << std::endl; }
The unique_ptr is not well-suited to linked structures