From 85c1e39dc85430e38b815a0a0082c9505b1213fe Mon Sep 17 00:00:00 2001 From: juan Date: Tue, 11 Oct 2022 16:57:12 +0800 Subject: [PATCH] Update pset0 --- semester3/pset0/7-3-central-list.c | 77 ++++++++++++++---------------- 1 file changed, 35 insertions(+), 42 deletions(-) diff --git a/semester3/pset0/7-3-central-list.c b/semester3/pset0/7-3-central-list.c index a06776f..45ac418 100644 --- a/semester3/pset0/7-3-central-list.c +++ b/semester3/pset0/7-3-central-list.c @@ -1,59 +1,52 @@ -#include #include #include -typedef struct stack { - int val; - struct stack *next; -} stack; +typedef struct listNode { + int id; + struct listNode *next; +} listNode; -stack *push(stack *st, int val) { - stack *new = malloc(sizeof(stack)); - new->next = st; - new->val = val; +listNode *appendNode(int id, listNode *head) { + listNode *new = malloc(sizeof(listNode)); + new->id = id; + new->next = NULL; + + head->next = new; return new; } -int isEmpty(stack *st) { return st == NULL; } - -int peek(stack *st) { return st->val; } - -stack *pop(stack *st) { - stack *tmp = st->next; - free(st); - return tmp; -} - int main(void) { - stack *st = NULL; + listNode* head = malloc(sizeof(listNode)); + listNode* ptr = head; int size = 0; - int in; - int last; - int lastUsed = 0; - int centFound = 0; - - while (scanf("%d,", &in) != EOF) { + int buf; + while ((scanf("%d,", & buf) != EOF)) { + ptr = appendNode(buf, ptr); size++; - if (!isEmpty(st) && peek(st) == in) { - st = pop(st); - } else if (lastUsed == 1 && last == in) { - st = pop(st); - st = pop(st); - centFound = 1; - } else { - if (!isEmpty(st)) { - last = peek(st); - lastUsed = 1; - } - // printf("PUSHING: %d\n", in); - st = push(st, in); + } + + if (size <= 1) { + printf("Yes"); + return 0; + } + + int ans[size]; + + head = head->next; + for (int i = 0; i < size; i ++) { + ans[i] = head->id; + head = head->next; + } + + int isCentral = 1; + for (int i = 0, end = size / 2; i < end; i++) { + if (ans[i] != ans[size - i - 1]) { + isCentral = 0; } } - if (size > 0 && isEmpty(st) && centFound == 1) { - printf("Yes"); - } else if (size == 1) { + if (isCentral == 1) { printf("Yes"); } else { printf("No");