Cześć,
Mam do zrealizowana zadanie, którego treść wkleiłem poniżej w postaci obrazka. Jeszcze niżej znajduje się kod programu który napisałem. Kod działa (dla poprawnych danych wejściowych daje odpowiednie rezultaty), wydaje mi się też, że nie jest najgorszy, ale nie jest niestety wystarczająco optymalny. Zrealizowany jest w oparciu o "zapętloną" listę jednokierunkową. Pomóżcie i powiedzcie, co mógłbym zmienić, aby ten program wykonywał się szybciej?
#include <stdio.h>
#include <stdlib.h>
typedef struct n {
int value;
struct n *next;
} node;
typedef struct {
node *begin;
node *end;
node *pos;
int size;
} list;
list *addToList(list *l, int i);
void processList(list *l, int numberOfOperations);
void printList(list *l);
void movePOSRight(list *l, int i);
void makeOperR(list *l);
void makeOperX(list *l);
int main(int argc, char **argv) {
int numberOfOperations = 0;
int x = 0;
list *l = malloc(sizeof(*l));
l->size = 0;
l->begin = l->end = l->pos = NULL;
if (scanf("%d", &x) == 1) {
numberOfOperations = x;
while (scanf("%d", &x) == 1) {
l = addToList(l, x);
}
if (l->size != 0) {
processList(l, numberOfOperations);
}
}
printList(l);
return 0;
}
list *addToList(list *l, int i) {
if (l->begin == NULL) {
l->begin = malloc(sizeof(l->begin));
l->begin->value = i;
l->pos = l->end = l->begin->next = l->begin;
} else {
l->end->next = malloc(sizeof(l->end->next));
l->end->next->value = i;
l->end->next->next = l->begin;
l->end = l->end->next;
}
l->size++;
return l;
}
void processList(list *l, int numberOfOperations) {
while (numberOfOperations--) {
if (l->pos->value % 2 == 0) {
makeOperR(l);
} else {
makeOperX(l);
}
}
}
void printList(list *l) {
int i;
node *n;
if (l == NULL || l->size == 0) {
printf("-1");
return;
}
n = l->pos;
printf("%d", n->value);
n = n->next;
for (i = 1; i < l->size; i++) {
printf(" %d", n->value);
n = n->next;
}
}
void makeOperX(list *l) {
node *tmp = l->pos->next;
l->pos->next = malloc(sizeof(l->pos->next));
l->pos->next->next = tmp;
l->pos->next->value = l->pos->value - 1;
l->size++;
movePOSRight(l, l->pos->value);
}
void makeOperR(list *l) {
int i = l->pos->next->value;
l->pos->next = l->pos->next->next;
l->size--;
movePOSRight(l, i);
}
void movePOSRight(list *l, int i) {
i = i % l->size;
while (i--) {
l->pos = l->pos->next;
}
}