이중연결리스트프로그램 예제코드에서 조건문을 달으신 이유를 모르겠습니다 ( feat.C언어로 쉽게쓴 자료구조 책 )
조회수 798회
안녕하세요.
'C언어로 쉽게쓴 자료구조'라는 책을 통해 복학준비 중인 학생입니다.
이중연결리스트를 통해 mp3 재생프로그램 만들기라는 예제를 보고 있다가
" 어... 여기서 왜 이런 조건문을 단 거지 " 라는 생각이 들어 글을 올립니다.
( 전체 프로그램의 일부분을 올리고 싶지만 소스코드란 것이 소설처럼 어떤 흐름을 타고 작성해나가는 것이라고 생각을 하고 있기에 전문을 올립니다. 오타 체크를 했으나 만약 있다면 애교로 생각해주세요 ㅎㅎ)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef char element[100];
typedef struct DListNode {
element data;
struct DListNode *llink;
struct DListNode *rlink;
}DListNode;
DListNode* current;
// 이중 연결 리스트를 초기화
void init(DListNode* phead)
{
phead->llink = phead;
phead->rlink = phead;
}
// 이중 연결 리스트의 노드를 출력
void print_dlist(DListNode* phead)
{
DListNode* p;
for (p = phead->rlink; p != phead; p = p->rlink)
{
if(p == current)
printf("<-| #%s# |->",p->data);
else
printf("<-| %s |->",p->data);
}
printf("\n");
}
// 노드 newnode를 노드 before의 오른쪽에 삽입한다.
void dinsert(DListNode *before, element data)
{
DListNode *newnode = (DListNode *)malloc(sizeof(DListNode));
strcpy_s(newnode->data, data,sizeof(data));
// 왜 '=연산자'를 납두고 strcpy()를 쓰는지 이 부분도 이해가 안 가네요.
// 이것 관련해서도 질문글 올렸습니다!
newnode->llink = before;
newnode->rlink = before->rlink;
before->rlink->llink = newnode;
before->rlink = newnode;
}
// 노드 removed를 삭제한다.
void ddelete(DListNode* head, DListNode* removed)
{
if (removed == head) return;
removed->llink->rlink = removed->rlink;
removed->rlink->llink = removed->llink;
free(removed);
}
int main(void)
{
char ch; // 조작키 변수
DListNode *head = (DListNode *)malloc(sizeof(DListNode)); // head 노드 선언
init(head); // head 노드 초기화
// 삽입
dinsert(head, "Mamamia");
dinsert(head, "Dancing Queen");
dinsert(head, "Fernando");
current = head->rlink;
print_dlist(head);
do {
printf("\n명령어를 입력하시오(<,>,q) : ");
ch = getchar();
if (ch == '<') {
current = current->llink;
if (current == head)
current = current->llink;
}
else if (ch == '>') {
current = current->rlink;
if (current == head)
current = current->rlink;
}
print_dlist(head);
getchar();
} while (ch != 'q'); // 조작키 변수가 q일 때까지 loop
// 동적 메모리 해제 코드를 여기에
}
제가 핵심적으로 이해가 안 되는 부분은
바로 위에 do-while문에서 if조건문의 존재이유가 이해가 안 됩니다.
do {
printf("\n명령어를 입력하시오(<,>,q) : ");
ch = getchar();
if (ch == '<') {
current = current->llink;
if (current == head)
current = current->llink;
}
else if (ch == '>') {
current = current->rlink;
if (current == head)
current = current->rlink;
}
print_dlist(head);
getchar();
} while (ch != 'q');
- current가 head인 경우를 처리하는 의도를 모르겠습니다.
- if문의 처리내용이 head = head->llink나 head = head->rlink인데 이 처리를 왜 하는지 모르겠습니다. 이미 if문 이전에 head = head->llink나 head = head->rlink 처리를 했는데 왜 또 하나요?
항상 오래 생각해보고 깊이 생각해보려해도
같은 시선에 바라보기만 하게되면 이렇게 질문을 드리게되네요.
또 어처구니 없는 실수나 생각이 짧은 것이 아니었기를 기도해봅니다.
감사합니다 :)
댓글 입력