알고리즘 공부

[C++] 백준 1158번 동적 배열 할당과 linkedlist c6001 경고

transfer_kk 2023. 3. 9. 19:36

문제

https://www.acmicpc.net/problem/1158

 

1158번: 요세푸스 문제

첫째 줄에 N과 K가 빈 칸을 사이에 두고 순서대로 주어진다. (1 ≤ K ≤ N ≤ 5,000)

www.acmicpc.net

나의 풀이

#include<iostream>
using namespace std;

struct Node {
	int data;
	struct Node* next;
};

class circleList {
public:
	circleList();
	void append(int data);
	void deletion(int n, int k);
private:
	Node* head;
	Node* tail;
	int listSize;
};

circleList::circleList() {
	head = NULL;
	tail = NULL;
	listSize = 0;
}

void circleList::append(int data) {
	Node* newNode = new Node;
	newNode->data = data;

	if (this->listSize == 0) {
		tail = head = newNode;
		head->next = tail->next = newNode;
	}
	else {
		tail->next = newNode;
		newNode->next = head;
		tail = newNode;
	}

	this->listSize++;
}

void circleList::deletion(int n, int k) {
	Node* preNode = head;
	Node* delNode = head;
	int count = 1;
	int* outputList = new int[n](); // 크기 k로 동적 할당하고 0으로 초기화
	int outputListIndex = 0;
	while (true) {

		if (listSize == 0) {
			break;
		}
		else if (count % k == 0) {
			outputList[outputListIndex] = delNode->data;
			outputListIndex++;
			preNode->next = delNode->next;
			delNode = preNode->next;
			listSize--;
		}
		else {
			preNode = delNode;
			delNode = preNode->next;
		}

		count++;
	}

	cout << '<';
	for (int i = 0; i < n; i++) { // n으로 수정
		cout << outputList[i];
		if (i != n - 1) { // 마지막 값 이후에는 ',' 출력하지 않도록 수정
			cout << ", ";
		}
	}
	cout << '>';
	delete[] outputList; // 동적 할당한 메모리 반환
}

int main() {
	int n, k;
	cin >> n >> k;
	circleList c;
	for (int i = 1; i <= n; i++) {
		c.append(i);
	}
	c.deletion(n, k);
	return 0;
}

환형 연결 리스트를 사용하여 문제를 풀었다.

동적 배열 할당 후 delete를 해주어야 메모리 누수가 발생하지 않아 꼭 delete를 사용해 지워준다.

하던 중 "c6001: 초기화되지 않은 메모리 'outputList[n-1]'을 사용하고 있습니다"라는 경고문이 떴는데  이를 방지하기 위해 new 연산자가 아닌 new() 연산자를 사용하여 배열의 모든 요소를 0으로 초기화 하였다.