자료구조

[자료구조] CircularDoubleLinkedList.c

mintuchel 2023. 5. 9. 22:47
// 백준 solved
// 원형 양방향 연결리스트
// cl->head 포인터를 통해 전체 리스트 접근

#pragma warning(disable:4996)
#include <stdio.h>
#include <stdlib.h>

typedef int CLdata ; // 자료형만 바꿔주기

typedef struct _node {
	struct _node* prev;
	CLdata data;
	struct _node* next;
}Node;

typedef struct _CircularDoubleLinkedList {
	Node* head;
}cl;

void CLInit(cl* clp) {
	clp->head = NULL;
}

void CLInsert(cl* clp, CLdata data) {
	Node* newNode = (Node*)malloc(sizeof(Node));
	newNode->data = data;

	// 첫번째 원소이면
	if (clp->head == NULL) {
		clp->head = newNode;
		newNode->next = newNode;
		newNode->prev = newNode;
	}
	// 중간번째 원소이면
	else {
		Node* temp = clp->head;
		while (temp->next != clp->head) {
			temp = temp->next;
		}

		newNode->prev = temp;
		newNode->next = temp->next;
		temp->next = newNode;
		clp->head->prev = newNode;
	}
}

// idx번째 원소 삭제
CLdata CLDelete(cl* clp, int idx) {

	// 마지막 원소 삭제
	// head 삭제
	Node* cur = clp->head;
	for (int i = 0; i < idx - 1; i++) {
		cur = cur->next;
	}

	CLdata retdata = cur->data;
	Node* delNode = cur;

	// head 삭제일때
	if (cur == clp->head) {
		clp->head->prev->next = clp->head->next;
		clp->head->next->prev = clp->head->prev;
		clp->head = cur->next;
	}
	else {
		cur->prev->next = cur->next;
		cur->next->prev = cur->prev;
	}

	free(delNode);
	return retdata;
}

int main() {
	cl clist;
	CLInit(&clist);
	
    // code
    
	return 0;
}