뎁스_2605의 블로그
글쓰기
로그인
회원가입
뎁스_2605
팔로우
통계
작성한 글
1
작성 댓글
0
가입 그룹
0
글
태그
댓글
팔로잉
팔로워
뎁스_2605
· 2년전
질문
이중 연결 리스트 질문
이중 연결 리스트를 사용해 상자와 다음 상자를 가르키는 숫자를 입력받고 상자의 위치와 상자를 여는 순서에 대한 코드를 작성 중입니다. 코드에 입력된 조건에 따르면 "(2) 보물상자 여는 순서를 출력" 에서 1 3 6 5 4 2가 출력되어야 하는데 1 3 6 5 2가 출력됩니다. 혹시 어디가 문제인지 알 수 있을까요 #include <stdio.h> #include <stdlib.h> typedef struct node { int num; int message; char check; struct node* prev; struct node* next; } Node; typedef struct { int countIndex; Node* tail; } List; void insertNode(List* list, int position, int element) { Node* preNode = list->tail; Node* newNode = (Node*)malloc(sizeof(Node)); newNode->message = element; newNode->check = 'C'; if (list->countIndex == 0) { newNode->next = newNode; newNode->prev = newNode; list->tail = newNode; } else { for (int i = 0; i < position; i++) { preNode = preNode->next; } newNode->next = preNode->next; newNode->prev = preNode; newNode->next->prev = newNode; preNode->next = newNode; if (position == list->countIndex) { list->tail = newNode; } } list->countIndex++; newNode->num = list->countIndex; } List* createList() { List* list = (List*)malloc(sizeof(List)); if (list == NULL) { printf("ERROR\n"); } else { list->tail = NULL; list->countIndex = 0; } return list; } void printList(List* list) { Node* node = list->tail->next; for (int i = 0; i < list->countIndex; i++) { printf("%d, %2d, %c\n", node->num, node->message, node->check); node = node->next; } } void findTreasure(List* list) { Node* node = list->tail->next; int count = 0; while (count <= list->countIndex) { if (node->check == 'C') { printf("%d ", node->num); node->check = 'O'; count++; } int message = node->message; if (message > 0) { for (int i = 0; i < message; i++) { node = node->next; if (node == list->tail->next) { node = node->next; } } } else if (message < 0) { for (int i = 0; i > message; i--) { node = node->prev; if (node == list->tail->next) { node = node->prev; } } } if (count == list->countIndex && node->check != 'O') { printf("%d ", node->num); node->check = 'O'; count++; } } printf("\n"); } int main() { int k; List* list; list = createList(); k = 2; insertNode(list, 0, k); k = -1; insertNode(list, 1, k); k = 3; insertNode(list, 2, k); k = -2; insertNode(list, 3, k); k = 2; insertNode(list, 4, k); k = -1; insertNode(list, 5, k); printf("(1) 보물상자의 위치를 나타내는 숫자 출력\n"); printList(list); getchar(); printf("(2) 보물상자 여는 순서를 출력"); getchar(); findTreasure(list); return 0; }
215
1
0
윈비
·
2023-05-11
혹시 4번째 보물 상자에는 보물이 담겨져 있지 않아서이지 않을지요?
더 보기