Skip to content

Instantly share code, notes, and snippets.

@itsjohncs
Created February 26, 2014 03:17
Show Gist options
  • Save itsjohncs/9222898 to your computer and use it in GitHub Desktop.
Save itsjohncs/9222898 to your computer and use it in GitHub Desktop.
#include <vector>
#include <iostream>
struct ListNode {
int data;
ListNode * next;
};
ListNode * construct_linked_list(std::vector<int> const & v) {
ListNode * head = NULL;
for (int i = static_cast<int>(v.size()) - 1; i >= 0; --i) {
ListNode * new_node = new ListNode;
new_node->data = v.at(i);
new_node->next = head;
head = new_node;
}
return head;
}
int main() {
// Get a series of numbers from the user and store them in a vector
std::vector<int> series;
std::cout << "Enter a series of numbers ending with a 0: " << std::flush;
while (true) {
int input;
std::cin >> input;
if (input == 0) {
break;
}
series.push_back(input);
}
// Convert the vector into a linked list
ListNode * list = construct_linked_list(series);
// Traverse through the linked list and print it out
std::cout << "Youre list is: ";
for (ListNode * i = list; i != NULL; i = i->next) {
std::cout << i->data << ", ";
}
std::cout << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment