Part 3
Task 1 - arrayShift.c
Note: It is possible to implement this more efficiently without using nested loops.
1
2
3
4
5
6
7
8
9
10
11
12 | void shift(int *arr, int size, int n) {
if (size <= 1) return;
n %= size;
for (int i = 0; i < n; i++) {
int tmp = arr[size - 1];
for (int j = size - 1; j > 0; j--) {
arr[j] = arr[j - 1];
}
arr[0] = tmp;
}
}
|
Task 2 - listShift.c
Note: It is possible to implement this more efficiently without using nested loops.
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 | int listLength(struct node *list);
struct node *shift(struct node *list, int n) {
int size = listLength(list);
if (size <= 1) return list;
n %= size;
for (int i = 0; i < n; i++) {
struct node *curr = list;
while (curr->next->next != NULL) {
curr = curr->next;
}
curr->next->next = list;
list = curr->next;
curr->next = NULL;
}
return list;
}
int listLength(struct node *list) {
int len = 0;
for (struct node *curr = list; curr != NULL; curr = curr->next) {
len++;
}
return len;
}
|
Task 3 - arrayInsertOrdered.c
| void insertOrdered(int *arr, int size, int value) {
int i;
for (i = size - 1; i >= 0; i--) {
if (value >= arr[i]) {
break;
}
arr[i + 1] = arr[i];
}
arr[i + 1] = value;
}
|
Task 4 - listInsertOrdered.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 | struct node *insertOrdered(struct node *list, int value) {
struct node *new = newNode(value);
if (list == NULL || value <= list->value) {
new->next = list;
return new;
}
struct node *curr = list;
while (curr->next != NULL && value > curr->next->value) {
curr = curr->next;
}
new->next = curr->next;
curr->next = new;
return list;
}
|