원형 연결 리스트: 마지막 노드가 첫 번째 노드를 가리키는 리스트
원형 연결 리스트는 마지막 노드를 head가, 첫 번째 노드는 head->link가 가리키고 있다.

ListNode *head;ListNode* insert_first(ListNode *head, element data)
{
ListNode *node = (ListNode *)malloc(sizeof(ListNode));
node->data = data;
if(head == NULL){
head = node;
node->link = head;
}
else{
node->link = head->link;
head->link = node;
}
return head;
}
ListNode* insert_last(ListNode *head, element data)
{
ListNode *node = (ListNode *)malloc(sizeof(ListNode));
node->data = data;
if(head == NULL){
head = node;
node->link = head;
}
else{
node->link = head->link;
head->link = node;
}
return head;
}
#include <stdio.h>
#include <stdlib.h>
typedef int element;
typedef struct ListNode{
element data;
struct ListNode *link;
} ListNode;
//리스트의 항목 출력
void print_list(ListNode* head)
{
ListNode* p;
if(head == NULL) return;
p = head->link;
do{
printf("%d->", p->data);
p = p->link;
}while (p != head->link);
}
listNode* insert_first(ListNode *head, element data)
{
ListNode *node = (ListNode *)malloc(sizeof(ListNode));
node->data = data;
if(head == NULL){
head = node; // head포인터가 node를 가리키게 함
node->link = head; // 첫 번째 노드가 된 node가 자기자신을 가리키게 함
}
else{
node->link = head->link;
head->link = node;
}
return head;
}
ListNode* insert_last(ListNode *head, element data)
{
ListNode *node = (ListNode *)malloc(sizeof(ListNode));
node->data = data;
if(head == NULL){
head = node;
node->link = head;
}
else{
node->link = head->link;
head->link = node;
head = node;
}
return head;
}
//테스트 프로그램
int main(void)
{
ListNode *head == NULL;
head = inset_last(head, 20);
head = inset_last(head, 30);
head = inset_last(head, 40);
head = inset_first(head, 10);
print_list(head);
return 0;
}
원형 연결리스트는 다음과 같은 곳에서 사용된다.
- 컴퓨터에서 하나의 CPU로 여러 개의 프로그램을 실행할 때
- 멀티 플래이어 게임
- 원형 큐 만들기
다음은 멀티 플레이어 게임의 코드이다
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef char element[100];
typedef struct ListNode{
element data;
struct ListNode *link;
}ListNode;
ListNode* insert_last(ListNode *head, element data)
{
ListNode *node = (ListNode)malloc(sizeof(ListNode));
strcpy(node->data, data);
if(head == NULL){
head = node;
node->link = head;
}
else{
node->link = head->link;
head->link = node;
head = node;
}
return head;
}
int main(void)
{
ListNode *head = NULL;
head = insert_last(head, "KIM");
head = insert_last(head, "PARK");
head = insert_last(head, "CHOI");
ListNode* p = head->link;
for(int i = 0; i < 10; i++){
printf("현재 차례=%s \n", p->data);
p = p->link;
}
return 0;
}