-
-
Save zer0page/cbd52e86a875f4e6149133c83f5f3311 to your computer and use it in GitHub Desktop.
for chris
This file contains 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> | |
// To execute C, please define "int main()" | |
typedef struct node{ | |
unsigned long val; | |
struct node *next; | |
}node_t; | |
node_t* prepend(node_t *head, node_t *n) { | |
if (n) { | |
n->next = head; | |
return n; | |
} else { | |
return head; | |
} | |
} | |
node_t* insert(node_t *head, node_t *n) { | |
node_t *orig = head; | |
if (!head) { | |
return n; | |
} else if (n && n->val < head->val){ | |
//prepend case | |
return prepend(head, n); | |
} | |
//insert case | |
while(head && head->next) { | |
if(n->val >= head->val && n->val < head->next->val) { | |
n->next = head->next; | |
head->next = n; | |
return head; | |
} | |
head = head->next; | |
} | |
//append case | |
head->next = n; | |
return orig; | |
} | |
void print_node(node_t *head) { | |
while(head){ | |
printf("node val is %lu\n", head->val); | |
head = head->next; | |
} | |
} | |
#define NUM_NODES 20 | |
unsigned long test_cases[] = { | |
0, | |
99999, | |
801, | |
801, | |
500, | |
0, | |
0, | |
99999, | |
}; | |
#define NUM_TEST_CASES (sizeof(test_cases)/sizeof(unsigned long)) | |
int main() { | |
static node_t nbuf[NUM_NODES]; | |
node_t *head = NULL; | |
printf("\nsetting up\n"); | |
for (int i = NUM_NODES-1; i >= 0; i--) { | |
node_t *n = &nbuf[i]; | |
n->val = 100 + i * 100; | |
head = prepend(head, n); | |
} | |
print_node(head); | |
printf("\ngenerating tests\n"); | |
static node_t tests[NUM_TEST_CASES]; | |
for(int i = 0; i < NUM_TEST_CASES; i++) { | |
tests[i].val = test_cases[i]; | |
print_node(&tests[i]); | |
} | |
printf("\ninserted nodes\n"); | |
for(int i = 0; i < NUM_TEST_CASES; i++) { | |
head = insert(head, &tests[i]); | |
} | |
print_node(head); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment