Skip to content

Instantly share code, notes, and snippets.

@ebal5
Created May 21, 2015 11:53
Show Gist options
  • Save ebal5/fcd306c8d2b096471136 to your computer and use it in GitHub Desktop.
Save ebal5/fcd306c8d2b096471136 to your computer and use it in GitHub Desktop.
insertion sort
#include <stdio.h>
#include <stdlib.h>
typedef struct _node {
int node_data;
struct _node *next;
}node;
node *newNode(int data){
node *ret = (node *)malloc(sizeof(node));
ret->node_data = data;
ret->next = NULL;
return ret;
}
void insertion_sort_node(node **head, node *newn){
node *current = *head;
if (current == NULL){
*head = newn;
return;
}
if(current->node_data > newn->node_data){
*head = newn;
newn->next = current;
return;
}
while(current->next != NULL){
if(current->next->node_data > newn->node_data){
newn->next = current->next;
current->next = newn;
return;
}
current = current->next;
}
current->next = newn;
return;
}
node *delete_node(node **head, int cutn){
node *current = *head;
node *ret = NULL;
if(current->node_data == cutn){
ret = current;
*head = current->next;
return ret;
}
while(current->next != NULL){
if(current->next->node_data == cutn){
ret = current->next;
current->next = ret->next;
return ret;
}
current = current->next;
}
return ret;
}
void print_list(node *head){
node *current = head;
printf("list: ");
while(current != NULL){
printf(" %d ", current->node_data);
current = current->next;
}
printf("\n");
}
int main (void){
node *head = NULL;
node *newn;
int data;
int flag;
do{
printf("put operationnumber\n");
printf("0: quit/ 1: new node/ 2: delete data\n");
scanf("%d", &flag);
switch (flag){
case 1: {
printf("node data > ");
scanf("%d", &data);
newn = newNode(data);
insertion_sort_node(&head, newn);
print_list(head);
break;
}
case 2: {
printf("cut data > ");
scanf("%d", &data);
if(head == NULL){
printf("Error!\n");
}else {
newn = delete_node(&head, data);
if(newn != NULL){
printf("\n%d deleted\n",data);
}else{
printf("%d not found\n", data);
}
print_list(head);
free(newn);
}
break;
}
default: break;
}
}while (flag != 0);
printf("will be quit......\n ");
if(head != NULL) free(head);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment