Algorithm

[C์–ธ์–ด] ์›ํ˜• ์—ฐ๊ฒฐ๋ฆฌ์ŠคํŠธ

say! 2023. 1. 12. 17:09
728x90

๐Ÿ”ต์›ํ˜• ์—ฐ๊ฒฐ๋ฆฌ์ŠคํŠธ

๋งˆ์ง€๋ง‰ ๋…ธ๋“œ๊ฐ€ ์ฒซ ๋ฒˆ์งธ ๋…ธ๋“œ๋ฅผ ๊ฐ€๋ฆฌํ‚ด

ํ•˜๋‚˜์˜ ๋…ธ๋“œ์—์„œ ๋‹ค๋ฅธ ๋ชจ๋“  ๋…ธ๋“œ๋กœ์˜ ์ ‘๊ทผ ๊ฐ€๋Šฅ

> ๋‹จ์ˆœ ์—ฐ๊ฒฐ๋ฆฌ์ŠคํŠธ๋ณด๋‹ค ์‚ฝ์ž…, ์‚ญ์ œ ๋” ์šฉ์ดํ•ด์ง

> ์‚ฝ์ž…,์‚ญ์ œ ์‹œ ์„ ํ–‰ ๋…ธ๋“œ๋ฅผ ํ•ญ์ƒ ์•Œ์•„์•ผํ•จ

ํ—ค๋“œ ํฌ์ธํ„ฐ๊ฐ€ ๋งˆ์ง€๋ง‰ ๋…ธ๋“œ ๊ฐ€๋ฆฌํ‚ด

 

๐ŸŸก ์›ํ˜• ์—ฐ๊ฒฐ๋ฆฌ์ŠคํŠธ ์ฝ”๋“œ

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

typedef int element;
typedef struct {
	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);
	printf("%d", p->data);	// ๋งˆ์ง€๋ง‰ ๋…ธ๋“œ ์ถœ๋ ฅ
}

// ์›ํ˜• ์—ฐ๊ฒฐ๋ฆฌ์ŠคํŠธ ์ฒ˜์Œ์— ์‚ฝ์ž…
ListNode* insert_frist(ListNode* head, element item) {
	ListNode* node = (ListNode*)malloc(sizeof(ListNode));
	node->data = item;

	if (head == NULL) {	// ์•„๋ฌด๊ฒƒ๋„ ์—†์—ˆ์„ ๋•Œ
		head = node;
		node->link = head;
	}
	else {
		node->link = head->link;
		head->link = node;
	}

	return head;	// ๋ณ€๊ฒฝ๋œ ํ—ค๋“œํฌ์ธํ„ฐ ๋ฐ˜ํ™˜
}

// ์›ํ˜• ์—ฐ๊ฒฐ๋ฆฌ์ŠคํŠธ ๋งˆ์ง€๋ง‰์— ์‚ฝ์ž…
ListNode* insert_last(ListNode* head, element item) {
	ListNode* node = (ListNode*)malloc(sizeof(ListNode));
	node->data = item;

	if (head == NULL) {	// ์•„๋ฌด๊ฒƒ๋„ ์—†์—ˆ์„ ๋•Œ
		head = node;
		node->link = head;
	}
	else {
		node->link = head->link;
		head->link = node;
		head = node;
	}

	return head;	// ๋ณ€๊ฒฝ๋œ ํ—ค๋“œํฌ์ธํ„ฐ ๋ฐ˜ํ™˜
}


int main() {
	ListNode* head = NULL;
	head = insert_frist(head, 10);
	head = insert_frist(head, 20);
	head = insert_last(head, 30);
	head = insert_frist(head, 40);
	print_list(head);
	return 0;
}

 

 

 

 

 

์›ํ˜•์—ฐ๊ฒฐ๋ฆฌ์ŠคํŠธ

์•ˆ๋…•ํ•˜์„ธ์š” ๊ณ ์ƒํ˜์ž…๋‹ˆ๋‹ค. ์˜ค๋Š˜์€ ์›ํ˜•์—ฐ๊ฒฐ๋ฆฌ์ŠคํŠธ์— ๋Œ€ํ•œ ๋‚ด์šฉ์„ ์ •๋ฆฌํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค. ์›ํ˜•์—ฐ๊ฒฐ๋ฆฌ์ŠคํŠธ๋ž€ ์‹œ์ž‘ ...

blog.naver.com