Created
April 21, 2014 16:28
-
-
Save Rag0n/11147887 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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