Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- typedef struct thing {
- int id;
- int last_id;
- /* last_id is only for the head. You _could_ make separate structs
- * for the head and its child nodes, but you _should_ keep them of
- * the same datatype to avoid unnecessary complexity...like having
- * to make a "superclass" that contains metadata about the structs
- * so that it's possible to use them interchangably. That would be
- * silly and unnecessary. Also, hot damn, look how perfectly these
- * lines are aligning at the right side. That was unintentional...
- */
- char *str;
- struct thing *next; /* You can also have *prev, if you need it. */
- } thing;
- thing *new_head(char *name){
- thing *t = malloc(sizeof(thing));
- t->id = 0;
- t->last_id = 0;
- t->next = 0;
- t->str = name;
- return t;
- }
- void push_thing(thing *head, char *name){
- thing *t = malloc(sizeof(thing)),
- *p = head;
- t->id = p->last_id++;
- t->next = 0;
- t->str = name;
- while(p->next){
- p = p->next;
- }
- p->next = t;
- }
- thing *find_thing(thing *head, int id){
- thing *p = head;
- while(p){
- if(p->id == id){
- return p;
- } else {
- p = p->next;
- }
- }
- return 0;
- }
- void destroy_list(thing *head){
- thing *p = head,
- *n = 0;
- while(p){
- n = p->next;
- free(p->str);
- free(p);
- p = n;
- }
- }
- char *randstr(){
- char *s = malloc(sizeof(char) * 16);
- int i = 0;
- while(i < 15){
- s[i++] = 0x61 + (rand() % 26);
- }
- s[i] = 0;
- return s;
- }
- void do_list_report(thing *head){
- thing *t = find_thing(head, 15);
- printf("object 15 is: %s\n", t->str);
- t = head;
- while(t){
- printf("ID #%02i = %s\n", t->id, t->str);
- t = t->next;
- }
- }
- int main(){
- int i;
- thing *heads[2]; // The tutorial I watched used a global list head and global id, which is crap. Avoid global variables unlesss you're either demonstrating something or writing a codegolf.
- srand(time(0));
- heads[0] = new_head(randstr());
- heads[1] = new_head(randstr());
- i = 20; // This is only kept small so the output readable. Go ahread and crank it up to something huge like 10,000 and watch C chew it up in seconds
- while(i--){
- push_thing(heads[0], randstr());
- push_thing(heads[1], randstr());
- }
- printf("List #1:\n");
- do_list_report(heads[0]);
- printf("\nList #2:\n");
- do_list_report(heads[1]);
- destroy_list(heads[0]);
- destroy_list(heads[1]);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement