알고리즘/자료구조

C언어 연결리스트 -요일 삽입

sshhhh 2023. 8. 24. 17:03

Source Code

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


	typedef struct ListNode
{
	char data[4];
	struct ListNode* link;
} listNode;

typedef struct
{
	listNode* head;
} linkedList_h;

linkedList_h* createLinkedList_h(void)
{
	linkedList_h* L;
	L = (linkedList_h*)malloc(sizeof(linkedList_h));
	L->head = NULL;
	return L;
}

void freeLinkedList_h(linkedList_h* L)
{
	listNode* p;
	while (L->head != NULL)
	{
		p = L->head;
		L->head = L->head->link;
		free(p);
		p = NULL;
	}
}

void printList(linkedList_h* L)
{
	listNode* p;
	printf("L = (");
	p = L->head;
	while (p != NULL)
	{
		printf("%s", p->data);
		p = p->link;
		if (p != NULL) printf(", ");
	}
	printf(") \n");
}

listNode* createNode(char* x)
{
	listNode* newNode;

	newNode = (listNode*)malloc(sizeof(listNode));

	strcpy(newNode->data, x);
	newNode->link = NULL;

	return newNode;
}


listNode* insertNode(linkedList_h* L, listNode* pre, char* x)
{
	listNode* newNode;
	newNode = createNode(x);


	if (L->head == NULL)
	{
		L->head = newNode;
		pre = newNode;
	}

	else
	{
		newNode->link = pre->link;
		pre->link = newNode;
		pre = newNode;

	}
	return pre;
}




void deleteNode(linkedList_h* L, listNode* p)
{
	listNode* pre = NULL;

	if (L->head == NULL)
		return;
	if (L->head->link == NULL)
	{
		free(L->head);
		L->head = NULL;
		return;
	}
	if (p == NULL)
		return;

	pre = L->head;

	if (pre == p)
	{
		L->head = L->head->link;
		return;

	}

	while (pre->link != p)
	{
		pre = pre->link;
	}
	pre->link = p->link;
	free(p);

}


listNode* searchNode(linkedList_h* L, char* x)
{
	listNode* temp;

	temp = L->head;

	while (temp != NULL)
	{
		if (strcmp(temp->data, x) == 0)
			return temp;
		temp = temp->link;
	}
	return NULL;
}



int main()
{
	linkedList_h* L = NULL;
	listNode* p = NULL;
	listNode* temp = NULL;

	L = createLinkedList_h();


	int num;

	char a[10000], b[10000], c[10000];

	while (1)
	{
		printf("1.삽입  2.출력  3.삭제   4.검색   5.끝 \n");
		scanf("\n%d", &num);

		switch (num)
		{

		case 1:
			printf("삽입할 요일을 입력하시오.\n");
			scanf("%s", a);
			p = insertNode(L, p, a);
			break;
		case 2:
			printList(L);
			break;
		case 3:
			printf("삭제할 요일을 입력하시오.\n");
			scanf("%s", b);
			temp = searchNode(L, b);
	


			if (temp)
				deleteNode(L, temp);
			else
				printf("삭제할 요일이 없다.\n");
			



			break;
		case 4:
			printf("검색할 요일을 입력하시오.\n");
			scanf("%s", c);
			p = searchNode(L, c);

			if (p == NULL)
				printf("찾는 데이터가 없습니다.\n");
			else
				printf("[%s]를 찾았습니다.\n", p->data);
			break;

		default:
			return 0;
		}

	}
	freeLinkedList_h(L);


	return 0;
}

 

실행 결과