Skip to content

Instantly share code, notes, and snippets.

@sahne
Created March 13, 2013 00:10
Show Gist options
  • Save sahne/c36e835e7c7dbb855076 to your computer and use it in GitHub Desktop.
Save sahne/c36e835e7c7dbb855076 to your computer and use it in GitHub Desktop.
linked list example (ugly hack)
/* disclaimer: this code is not written very well, but it's late here */
#include <iostream>
using namespace std;
struct Number_Node
{
int number;
struct Number_Node *next_number;
};
struct Number_Node *
addNode(struct Number_Node *head, struct Number_Node *n)
{
/* head is null so n is our new head */
if (!head) {
head = n;
return head;
}
/* list is already sorted but new element is smaller than head,
* therefor it will be our new head
*/
if (n->number < head->number) {
n->next_number = head;
return n;
}
/* iterate through list */
Number_Node *next = head->next_number;
Number_Node *prev = head;
while(next) {
/* if the next element is larger insert n in between */
if (next->number > n->number) {
n->next_number = next;
prev->next_number = n;
return head;
}
prev = next;
next = next->next_number;
}
/* no element found, so check if it's smaller or greater than the last
* one and either append it to the end or before the last element
*/
if (!next)
if (prev->number > n->number) {
n->next_number = prev;
prev->next_number = next;
} else
prev->next_number = n;
/* return head */
return head;
}
int
main(void)
{
Number_Node *h = NULL;
Number_Node *n = NULL;
int input;
do {
cout << "Enter Number:";
cin >> input;
if (input == -1)
break;
n = new Number_Node;
n->number = input;
n->next_number = NULL;
/* this function will add the node within the sorted list */
h = addNode(h, n);
} while(1);
n = h;
while (n) {
cout << n->number << endl;
n = n->next_number;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment