Add implementation list

This commit is contained in:
dang hai 2019-07-07 13:20:11 -07:00
parent ab3173f581
commit e4d0fc93f6
4 changed files with 144 additions and 0 deletions

View File

@ -0,0 +1,12 @@
CC = gcc
CFLAGS = -g -c -Wall
all: main
main: main.o list.o
$(CC) -g main.o list.o -o main
list.o: list.c
$(CC) $(CFLAGS) list.c
clean:
rm *o main

View File

@ -0,0 +1,73 @@
#include <assert.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include "list.h"
#define L List_T
/* Initial list */
L List_init (void) {
L list;
list = (L) malloc(sizeof(L));
list->next = NULL;
return list;
}
/* Push an element into top of the list */
L List_push(L list, void *val) {
L new_elem = (L)malloc(sizeof(L));
new_elem->val = val;
new_elem->next = list;
return new_elem;
}
/* Length of list */
int List_length(L list) {
int n;
for(n = 0; list; list=list->next)
n++;
return n;
}
/* Convert list to array */
void **List_toArray(L list) {
int i, n = List_length(list);
void **array = (void **)malloc((n+1) *sizeof(*array));
for(i = 0; i < n; i++) {
array[i] = list->val;
list = list->next;
}
array[i] = NULL;
return array;
}
/* Create and return a list */
L List_list(L list, void *val, ...) {
va_list ap;
L *p = &list;
va_start(ap, val);
for(; val; val = va_arg(ap, void *)) {
*p = malloc(sizeof(L));
(*p)->val = val;
p = &(*p)->next;
}
*p = NULL;
va_end(ap);
return list;
}
/* Append 2 lists together */
L List_append(L list, L tail) {
L *p = &list;
while((*p)->next) {
p = &(*p)->next;
}
*p = tail;
return list;
}

View File

@ -0,0 +1,23 @@
#ifndef __LIST__
#define __LIST__
#define L List_T
typedef struct L *L;
struct L {
void *val;
L next;
};
extern L List_init(void);
extern L List_push(L list, void *val);
extern int List_length(L list);
extern void **List_toArray(L list);
extern L List_append(L list, L tail);
extern L List_list(L list, void *val, ...);
/* TODO */
extern L List_copy(L list);
extern int List_pop(L *list);
#undef L
#endif

View File

@ -0,0 +1,36 @@
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include "list.h"
void print_list(char **array) {
int i;
for( i = 0; array[i]; i++)
printf("%s", array[i]);
printf("\n");
}
int main() {
List_T list1, list2, list3;
char **str1 = (char **)malloc(100* sizeof(char *));
list1 = List_init();
list1 = List_push(list1, "Dang ");
list1 = List_push(list1, "Hoang ");
list1 = List_push(list1, "Hai ");
printf("List 1: ");
str1 = (char **)List_toArray(list1);
print_list(str1);
list2 = List_init();
list2 = List_list(list2, "Mentor ", "Graphics ", "Siemens", NULL);
printf("List 2: ");
print_list((char **)List_toArray(list2));
list3 = List_append(list1, list2);
printf("Test append list2 into list1: ");
print_list((char **)List_toArray(list3));
return 0;
}