Untitled

mail@pastecode.io avatar
unknown
c_cpp
7 months ago
2.5 kB
3
Indexable
Never
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node{
    long long val;
    struct node *nxt; 
};
typedef struct node unit;
char str[109];
signed main(){
    unit *head=(unit*)malloc(sizeof(unit)),*tail=(unit*)malloc(sizeof(unit));
    int exist=0;
    while(scanf(" %s",str)!=EOF){
        if(str[0]=='p'){ //印出陣列
            if(exist==0) //陣列不存在
                printf("\n");
            else{ //存在就照順序列印
                unit *pos=head;
                while(pos!=NULL){
                    printf("%lld ",pos->val); 
                    pos=pos->nxt; 
                }
                printf("\n");
            }
        }
        if(str[0]=='a'){ //在結尾插入
            unit *cur=(unit*)malloc(sizeof(unit)); 
            scanf(" %lld",&(cur->val)); 
            cur->nxt=NULL; 
            if(exist==0){ 
                head=cur;
                tail=head;
            }
            else{         
                tail->nxt=cur;
                tail=cur;
            }
            printf("APPEND_SUCC\n");
            exist=1;
        }
        if(str[0]=='s'){
            long long x;
            scanf(" %lld",&x); 
            int fail=1;
            unit *pos=head; 
            while(pos!=NULL){ //遍歷linked list
                unit *tem=pos;
                if(tem->val==x){
                    fail=0; //找到符合的數字 
                } 
                pos=pos->nxt; //指標指向下一個
            }
            if(fail) //沒找到target
                printf("SEARCH_FAIL\n");
            else //找到target
                printf("SEARCH_SUCC\n");
        }
        if(str[0]=='u'){ //更新
            long long x,y;
            scanf(" %lld %lld",&x,&y);
            int fail=1;
            unit *pos=head; 
            while(pos!=NULL){ //遍歷linked list
                if(pos->val==x){ //找到target
                    pos->val=y; //更新數字
                    fail=0; //設為0表示成功
                }
                pos=pos->nxt;
            }
            if(fail) //更新失敗
                printf("UPDATE_FAIL\n");
            else //更新成功
                printf("UPDATE_SUCC\n");

        }
    }
    unit *pos=head;
    while(pos!=NULL){ 
        unit *tem=pos;
        pos=pos->nxt; 
        free(tem);//清空linked list元素
    }
}
Leave a Comment