Data Structure – 노드 이용 원형 연결 리스트

Circle List (Node)

#include <stdio.h>
#include <stdlib.h>

typedef struct LinkNode {
	int data;
	struct ListNode *link;
}ListNode;

ListNode * insert_first(ListNode *head, int item) {
	if (head == NULL) {
		head = (ListNode*)malloc(sizeof(ListNode));
		head->data = item;
		head->link = head;
	}
	else {
		ListNode *p = (ListNode*)malloc(sizeof(ListNode));
		p->data = item;
		p->link = head->link;
		head->link = p;
	}
	return head;
}

ListNode * insert_last(ListNode *head, int item) {
	ListNode *p = (ListNode*)malloc(sizeof(ListNode));
	p->data = item;
	p->link = head->link;
	head->link = p;
	head = p;
	return head;
}
ListNode * delete_first(ListNode *head) {
	if (head == NULL) {
		printf("리스트가 비었습니다");
		return NULL;
	}

	ListNode *p;
	p = head->link;
	head->link = p->link;
	free(p);

	return head;
}
int print_list(ListNode *head) {
	if (head == NULL) {
		printf("리스트가 비었습니다");
		return NULL;
	}

	ListNode *p=head->link;
	while (p!= head) {
		printf("%d ", p->data);
		p = p->link;
	}
	printf("%d\n", p->data);
}

int main() {
	ListNode *list = NULL;

	list = insert_first(list, 10);
	print_list(list);
	list = insert_first(list, 20);
	print_list(list);
	list = insert_first(list, 30);
	print_list(list);

	list = insert_last(list, 40);
	print_list(list);
	list = insert_last(list, 50);
	print_list(list);
	list = delete_first(list);
	print_list(list);

	return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *