Skip to content

Instantly share code, notes, and snippets.

@Rag0n
Created April 21, 2014 16:28
Show Gist options
  • Save Rag0n/11147887 to your computer and use it in GitHub Desktop.
Save Rag0n/11147887 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct node
{
int data;
struct node* next;
};
void printList(struct node* head)
{
struct node* current = head->next;
while(current != NULL)
{
printf("%d\n", current->data);
current = current->next;
}
}
void sortedInsert(struct node* head, int data)
{
struct node* newNode;
newNode = (struct node*)malloc(sizeof(struct node));
newNode->data = data;
if (head->next == NULL || head->next->data >= newNode->data)
{
newNode->next = head->next;
head->next = newNode;
}
else
{
struct node* current = head;
while(current->next != NULL && current->next->data < newNode->data)
{
current = current->next;
}
newNode->next = current->next;
current->next = newNode;
}
}
void sort(struct node *head, struct node *sortedhead)
{
struct node* current = head->next;
while(current != NULL)
{
sortedInsert(sortedhead, current->data);
current = current->next;
}
}
void push(struct node *head, int data)
{
struct node *newNode;
newNode = (struct node*)malloc(sizeof(struct node));
newNode->data = data;
newNode->next = head->next;
head->next = newNode;
}
int main(int argc, char const *argv[])
{
struct node* head = NULL, *sortedhead = NULL;
head = (struct node*)malloc(sizeof(struct node));
sortedhead = (struct node*)malloc(sizeof(struct node));
push(head, 2);
push(head, 1);
push(head, 5);
push(head, 3);
sort(head, sortedhead);
printList(head);
printf("======\n");
printList(sortedhead);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment