ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [C] Doubly Circular Linked List기반의 ADT List 연산 구현
    Programming/C++ 2021. 2. 5. 00:42

    c++의 구조체를 이용해서 직접 Doubly Circular Linked List를 구현해봤다

    구현한 총 연산은 create, traversal, insert(first, middle, last), delete(first, middle, last)

    typedef struct Node {
    	int data;
    	struct Node* next;
    	struct Node* prev;
    }Node;
    
    void create(Node* head) {
    	head = NULL;
    }
    
    void traversal(Node* head) {
    	Node* cur = head;
    	if (head == NULL)return;
    	do {
    		printf("%d ", cur->data);
    		cur = cur->next;
    	} while (cur!= head);
    	printf("\n");
    }
    
    Node* insertFirst(Node* head, int data) {
    	Node* node = (Node*)malloc(sizeof(Node));
    	node->data = data;
    	if (head == NULL) {
    		node->next = node;
    		node->prev = node;
    	}
    	else {
    		node->next = head;
    		node->prev = head->prev;
    		head->prev->next = node;
    		head->prev = node;
    	}
    	head = node;
    	return head;
    }
    
    Node* insertLast(Node* head, int data) {
    	Node* node = (Node*)malloc(sizeof(Node));
    	node->data = data;
    	if (head == NULL) {
    		node->next = node;
    		node->prev = node;
    		head = node;
    	}
    	else {
    		node->next = head;
    		node->prev = head->prev;
    		head->prev->next = node;
    		head->prev = node;
    	}
    	return head;
    }
    
    Node* insert(Node* head, int data, int pos) {
    	Node* node = (Node*)malloc(sizeof(Node));
    	node->data = data;
    	
    	Node* pre = head,*next;
    	for (size_t i = 0; i < pos-1; i++)
    		pre = pre->next;
    
    	node->prev = pre;
    	node->next = pre->next;
    
    	pre->next->prev = node;
    	pre->next = node;
    
    	return head;	
    }
    
    Node* deleteFirst(Node* head) {
    	if (head == NULL)return NULL;
    
    	head->next->prev = head->prev;
    	head->prev->next = head->next;
    
    	Node* node = head;
    	head = head->next;
    	free(node);
    
    	return head;
    }
    
    Node* delete(Node* head,int pos) {
    	if (head == NULL)return NULL;
    
    	Node* pre = head;
    	for (size_t i = 0; i < pos - 1; i++)
    		pre = pre->next;
    
    	Node* node = pre->next;
    	node->next->prev = pre;
    	pre->next = node->next;
    
    	free(node);
    
    	return head;
    }
    
    Node* deleteLast(Node* head) {
    	if (head == NULL)return NULL;
    
    	Node* pre = head->prev->prev;
    	Node* cur = pre->next;
    
    	Node* node = cur;
    	pre->next = cur->next;
    	cur->next->prev = pre;
    
    	free(node);
    
    	return head;
    }

    코드만 보고는 헷갈렸는데 그림 그려가면서 순서를 정리하니까 감이 잡힌다

    고민의 흔적

Designed by Tistory.