Created
November 23, 2010 09:41
-
-
Save erenon/711521 to your computer and use it in GitHub Desktop.
insert after n
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 <stdlib.h> | |
#include <string.h> | |
typedef struct _list { | |
int value; | |
struct _list *next; | |
} list; | |
int get_list_len(list *head) { | |
int len=0; | |
while (head != NULL) { | |
head = head->next; | |
len++; | |
} | |
return len; | |
} | |
void list_append(list *head, list *item) { | |
while (head->next != NULL) { | |
head = head->next; | |
} | |
head->next = item; | |
} | |
void insert_after_n(list *head, list *item, int n) { | |
int len, i; | |
len = get_list_len(head); | |
if (len >= n) { | |
for (i=1; i < n; i++) { | |
head = head->next; | |
} | |
item->next = head->next; | |
head->next = item; | |
} else { | |
list_append(head, item); | |
} | |
} | |
/*TEST ONLY*/ | |
list *create_item(int value) { | |
list *item; | |
item = (list *)malloc(sizeof(list)); | |
//if null die | |
item->value = value; | |
item->next = NULL; | |
return item; | |
} | |
/*TEST ONLY*/ | |
void list_print(list *head) { | |
while (head) { | |
printf("%d ", head->value); | |
head = head->next; | |
} | |
} | |
/*TEST ONLY*/ | |
void list_delete(list *head) { | |
list *next; | |
while (head) { | |
next = head->next; | |
free(head); | |
head = next; | |
} | |
} | |
/*TEST ONLY*/ | |
int main() { | |
list *head; | |
head = create_item(0); | |
insert_after_n(head, create_item(1), 2); | |
insert_after_n(head, create_item(2), 3); | |
insert_after_n(head, create_item(4), 4); | |
insert_after_n(head, create_item(5), 5); | |
insert_after_n(head, create_item(3), 3); | |
list_print(head); | |
list_delete(head); | |
printf("\n"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment