Info1-Uebungen/ub10/singlyLinkedList.c

81 lines
1.4 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
typedef struct person {
char name[50];
int age;
} person;
typedef struct Node {
void *content;
struct Node *next;
} Node;
Node *newNode(void *content) {
Node *ret = (Node *)malloc(sizeof(Node));
if (ret == NULL)
return NULL;
ret->content = content;
ret->next = NULL;
return ret;
}
void appendNode(Node *head, Node *newTail) {
Node *tail = head;
while (tail->next != NULL) {
tail = tail->next;
}
tail->next = newTail;
}
void delTail(Node *head) {
printf("deleting tail\n");
Node *tail = head;
while (tail->next->next != NULL) {
tail = tail->next;
}
free(tail->next);
tail->next = NULL;
}
void printList(Node *head) {
int count = 0;
Node *h = head;
while (h != NULL) {
printf("%s : %d yeares old -> ", ((person *)h->content)->name,
((person *)h->content)->age);
count += 1;
h = h->next;
}
printf("\n%d nodes long\n", count);
}
int main() {
person p1 = {"alice", 23};
person p2 = {"bob", 30};
person p3 = {"mark", 48};
person p4 = {"bob2", 60};
Node *np1 = newNode(&p1);
Node *np2 = newNode(&p2);
Node *np3 = newNode(&p3);
Node *np4 = newNode(&p4);
Node *head = np1;
appendNode(head, np2);
appendNode(head, np3);
appendNode(head, np4);
printList(head);
delTail(head);
printList(head);
while (head->next != NULL) {
delTail(head);
}
free(head);
return 0;
}