Skip to content

Instantly share code, notes, and snippets.

@ktnyt
Last active August 29, 2015 14:02
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 ktnyt/be0bc865eccf37e2146c to your computer and use it in GitHub Desktop.
Save ktnyt/be0bc865eccf37e2146c to your computer and use it in GitHub Desktop.
Self referencing list
#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