top coder 가 되기위해
교수님께서 말씀하시길 창조적인 코더도 물론 중요하지만 남의 코드에 오류와 메커니즘을 이해하는 것 또한 중요하다 하셨다.
#include<stdio.h>
#include<stdlib.h>
struct item
{
int score;
struct item *next;
};
void append(struct item** ppS, struct item** ppE,int num);
void del_end(struct item** ppS, struct item** ppE);
void print_all(struct item* pStart);
int main(void)
{
struct item* pStart = NULL;
struct item* pEnd = NULL;
int data;
int choice;
printf("choice(1번) -----> 데이터 추가\n");
while (1==1)
{
printf("choice: ");
scanf_s("%d", &choice);
if (choice == 1)
{
printf("추가할 데이터 입력: ");
scanf_s("%d", &data);
append(&pStart, &pEnd, data);//<-data plus
}
else
{
printf("종료\n");
break;
}
}
print_all(pStart);//data display
del_end(&pStart, &pEnd);//end Remove
print_all(pStart);//data display
return 0;
}
void append(struct item** ppS, struct item** ppE, int num)
{
struct item *cur = *ppS;
struct item *p = NULL;
p = (struct item*)malloc(sizeof(struct item));
if (p == NULL)
{
printf("동적할당 실패!!!\n");
return;
}
else
{
p->score = num;
p->next = NULL;
if (*ppS == NULL)//데이터가 처음 들어갈때
{
*ppS = p;
*ppE = p;
}
else
{
while (cur->next != NULL)
{
cur = cur->next;
}
cur->next = p;
*ppE = p;
}
}
}
void del_end(struct item** ppS ,struct item** ppE)
{
struct item *pFree = NULL;
struct item *cur = *ppS;
struct item *cur_next = cur->next;
if (cur == NULL)
{
printf("삭제할 데이터가 없습니다.\n");
return;
}
else//cur != NULL
{
if (cur_next == NULL)
{
printf("삭제할 데이터는 한개밖에 없습니다.\n");
*ppS = NULL;
*ppE = *ppS;
free(cur);
}
else
{
while (cur_next->next != NULL)
{
cur = cur->next;
cur_next = cur_next->next;
}
pFree = cur_next;
cur->next = NULL;
*ppE = cur;
free(pFree);
}
}
}
void print_all(struct item* pStart)
{
printf("START--> ");
if (pStart == NULL)
{
printf("출력할 데이터가 없습니다.\n");
return;
}
else
{
while (pStart != NULL)
{
printf("%d", pStart->score);
pStart = pStart->next;
if (pStart != NULL)
{
printf("--> ");
}
}
printf(" END\n");
}
}