Skip to content

Instantly share code, notes, and snippets.

@Mic92
Created November 24, 2011 12:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Mic92/1391272 to your computer and use it in GitHub Desktop.
Save Mic92/1391272 to your computer and use it in GitHub Desktop.
List implementation in C
#include <stdlib.h>
#include <stdio.h>
typedef struct _IntList {
int current;
struct _IntList *next;
} IntList;
void Insert(IntList *l, int n) {
if (l == NULL) return;
while(l->next!=NULL && l->next->current < n)
l = l->next;
IntList *elem = (IntList *) malloc(sizeof(IntList));
elem->current = n;
elem->next = l->next;
l->next = elem;
}
void Insert2(IntList *l, int n) {
if(l == NULL) return;
if (l->next != NULL && l->next->current < n)
return Insert2(l->next, n);
IntList *elem = (IntList *) malloc(sizeof(IntList));
elem->current = n;
elem->next = l->next;
l->next = elem;
}
int main(int argc, char *argv[]) {
IntList list3 = {3, NULL};
IntList list2 = {2, &list3};
IntList list1 = {1, &list2};
Insert(&list1, 2);
Insert(&list1, 6);
Insert(&list1, 5);
Insert(&list1, 4);
Insert(&list1, 0);
Insert(&list1, 0);
Insert(&list1, 0);
Insert2(&list1, 6);
Insert2(&list1, 5);
Insert2(&list1, 0);
IntList *next = list1.next;
while (next != NULL) {
printf("%i\n", next->current);
next = next->next;
}
return 1;
}
#include <stdio.h>
#include <stdlib.h>
typedef struct lElem *IntList;
typedef struct lElem {
int nr;
IntList next;
} lElemType;
int readNumber() {
int n = 0;
printf("I need a number: ");
scanf("%d", &n);
return n;
}
void printList(IntList l) {
int i;
if (l==NULL)
printf("List is empty\n");
else {
i = 1;
while (l != NULL) {
printf("%d. value: %d\n", i, l->nr);
l=l->next;
i++;
}
}
}
void newList(IntList *list) {
*list=NULL;
}
void Insert(IntList *l, int n) {
IntList new;
new = (IntList) malloc (sizeof(lElemType));
new->nr=n;
if (*l == NULL) {
*l = new;
new->next = NULL;
} else if ((*l)->nr > n){
new->next = *l;
*l= new;
} else {
IntList insertPoint = *l;
while (insertPoint->next != NULL && insertPoint->next->nr < n)
insertPoint = insertPoint->next;
new->next = insertPoint->next;
insertPoint->next=new;
}
}
int main() {
IntList l;
newList(&l);
int n;
n = readNumber();
while (n > 0) {
Insert(&l, n);
n = readNumber();
}
printList(l);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment