linked_list
unknown
c_cpp
2 years ago
2.0 kB
13
Indexable
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node{
long long val;
struct node *nxt; //val紀錄數值,nxt指向下一個
};
typedef struct node unit;
char str[109];
signed main(){
unit *head=(unit*)malloc(sizeof(unit)),*tail=(unit*)malloc(sizeof(unit));
//head指向list開頭,tail指向list結尾
int exist=0;//表示list是否已存在
while(scanf(" %s",str)!=EOF){
if(str[0]=='p'){
if(exist==0)
printf("\n");
else{
unit *pos=(unit*)malloc(sizeof(unit)); //pos開出空間
pos=head; //指標設成指向開頭
while(pos!=NULL){
printf("%lld ",pos->val); //遍歷輸出list內的數字
pos=pos->nxt; //往後指下一個元素
}
printf("\n");
free(pos); //將pos的記憶體釋放掉
}
//printf("exist= %d \n",exist);
}
if(str[0]=='a'){
unit *cur=(unit*)malloc(sizeof(unit));
scanf(" %lld",&(cur->val)); //輸入到cur指向的node結構中的val
cur->nxt=NULL; //新節點後一個先設成null
//printf("finish\n");
if(exist==0){ //如果序列未創建
head=cur;
tail=head;
}
else{ //序列已建立
tail->nxt=cur;
tail=cur;
}
//free(cur);
printf("APPEND_SUCC\n");
exist=1;
}
}
unit *pos=(unit*)malloc(sizeof(unit));
pos=head;
while(pos!=NULL){ //遍歷linked list
//printf("%lld ",pos->val);
unit *tem=pos;
free(tem);//釋放linked list每個記憶體
pos=pos->nxt; //往linked list後面繼續跑
}
free(head); //釋放開頭的記憶體
free(tail); //釋放結尾的記憶體
//printf("finish\n");
}Editor is loading...
Leave a Comment