C 언어 --- - 링크 에 고리 가 있 는 지 판단

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

#define CNT 10

typedef struct node{
	int value;
	struct node *next;
}list_node_t;

list_node_t *creat_node(int value);

void list_print_node(list_node_t *node_p);
void list_print_all(list_node_t *node_p);

list_node_t *list_insert_end_node(list_node_t *node_p, int value);
void list_is_ring(list_node_t *node_p);

void list_free(list_node_t *node_p);

int main(int argc, char **argv)
{
	int i;
	list_node_t *head = NULL;

	for(i = 0; i < CNT; i++)
	{
		head = list_insert_end_node(head, i+1);
	}
	list_print_all(head);

	list_is_ring(head);

	list_free(head);

	return 0;
}

list_node_t *creat_node(int value)
{
	list_node_t *node_p;

	node_p = malloc(sizeof(list_node_t));
	if(node_p == NULL)
	{
		fprintf(stderr, "Malloc for creating node failed.
"); exit(1); } node_p->value = value; node_p->next = NULL; return node_p; } void list_print_node(list_node_t *node_p) { fprintf(stdout, "p = %p value = %2d p->next = %p
", node_p, node_p->value, node_p->next); } void list_print_all(list_node_t *node_p) { list_node_t *head = node_p; while(head) { list_print_node(head); head = head->next; if(head == node_p) break; } } list_node_t *list_insert_end_node(list_node_t *node_p, int value) { list_node_t *new_node = creat_node(value); if(new_node == NULL) { fprintf(stderr, "Creat new node failed.
"); exit(1); } if(node_p == NULL) { node_p = new_node; new_node->next = node_p; return node_p; } list_node_t *p = node_p; while(p->next) { p = p->next; if(p->next == node_p) break; } p->next = new_node; new_node->next = node_p; return node_p; } void list_is_ring(list_node_t *node_p) { list_node_t *prev, *cur; prev = cur = node_p; while(1) { prev = prev->next; //cur = cur->next->next; if(prev == NULL) { fprintf(stdout, "Is not ring.
"); break; } else { fprintf(stdout, "Is ring.
"); break; } } } void list_free(list_node_t *node_p) { list_node_t *p = node_p; while(p->next) { if(p->next == node_p) break; free(p); p = p->next; } free(p); }

좋은 웹페이지 즐겨찾기