-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path6-linked-list.c
102 lines (93 loc) · 2.38 KB
/
6-linked-list.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME_LENGTH 16
typedef struct Person
{
char name[MAX_NAME_LENGTH];
int age;
struct Person *next;
} Person;
Person* createPerson(const char* name, int age) {
Person* newPerson = (Person*)malloc(sizeof(Person));
if (newPerson == NULL) {
return NULL;
}
strncpy(newPerson->name, name, MAX_NAME_LENGTH - 1);
newPerson->name[MAX_NAME_LENGTH - 1] = '\0';
newPerson->age = age;
newPerson->next = NULL;
return newPerson;
}
Person* addPerson(Person* head, const char* name, int age) {
// Create new person node
Person* newPerson = createPerson(name, age);
// Return existing list if creation failed
if (newPerson == NULL) {
return head;
}
// If list is empty, new person becomes head
if (head == NULL) {
return newPerson;
}
// Traverse to end of list
Person* current = head;
while (current->next != NULL) {
current = current->next;
}
// Add new person to end of list
current->next = newPerson;
return head;
}
void printPerson(Person *p)
{
printf("%s (%d)", p->name, p->age);
}
void printPersonList(Person *l)
{
while (l != NULL)
{
printf(" -> ");
printPerson(l);
l = l->next;
}
printf(".\n");
}
Person *insertPersonSortedByAge(Person *head, const char* name, int age) {
// Create new person node
Person* newPerson = createPerson(name, age);
// Return existing list if creation failed
if (newPerson == NULL) {
return head;
}
// If list is empty, new person becomes head
if (head == NULL) {
return newPerson;
}
// If new person is younger than head, insert at beginning
if (age < head->age) {
newPerson->next = head;
return newPerson;
}
// Find insertion point by traversing until we find someone older
Person* current = head;
while (current->next != NULL && current->next->age < age) {
current = current->next;
}
// Insert new person between current and current->next
newPerson->next = current->next;
current->next = newPerson;
return head;
}
int main(int argc, char *argv[])
{
Person *personlist = calloc(1, sizeof(Person));
personlist = createPerson("Kwik", 3);
personlist = addPerson(personlist, "Kwek", 5);
personlist = addPerson(personlist, "Kwak", 7);
printPersonList(personlist);
printf("\n");
personlist = insertPersonSortedByAge(personlist, "Kwuk", 4);
printPersonList(personlist);
printf("\n");
}