Last active
August 29, 2015 14:02
-
-
Save ktnyt/be0bc865eccf37e2146c to your computer and use it in GitHub Desktop.
Self referencing list
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> | |
#include <stdlib.h> | |
#include <string.h> | |
// struct listじゃなくてlistで定義できるおまじない | |
typedef struct _list { | |
char* name; | |
struct _list* next; | |
} list; | |
// 空の先頭要素 | |
list* listHead() { | |
list* p = (list*)malloc(sizeof(list)); | |
p->name = NULL; | |
p->next = NULL; | |
return p; | |
} | |
// nameで初期化した要素 | |
list* initList(char* name) { | |
list* p = (list*)malloc(sizeof(list)); | |
p->name = name; | |
p->next = NULL; | |
return p; | |
} | |
// 最後のノードを探す | |
list* lastNode(list* p) { | |
list *last = p; | |
while(last->next != NULL) { | |
last = last->next; | |
} | |
return last; | |
} | |
// nameの要素を追加する | |
void pushList(list* p, char* name) { | |
p = lastNode(p); | |
list* q = initList(name); | |
p->next = q; | |
} | |
int main(int argc, char* argv[]) { | |
// 空白の先頭要素 | |
list* h = listHead(); | |
int i; | |
for(i = 1; i < argc; ++i) { | |
pushList(h, argv[i]); | |
} | |
while((h = h->next) != NULL) { | |
if(h->name != NULL) { | |
printf("%s\n", h->name); | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment