#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct listNode *node_p;
struct listNode {
char data[10];
node_p link;
};
node_p L = NULL;
void printList(node_p L);
node_p addNode(node_p L, char *x);
node_p searchNode(node_p L, char *x);
node_p insertNode(node_p L, node_p p, char *x);
node_p deleteNext(node_p L, node_p p);
void printList(node_p L)
{
node_p p;
printf("\n(");
p = L;
while (p != NULL) {
printf("%s", p->data);
p = p->link;
if (p != NULL) printf(", ");
}
printf(")\n");
}
void main()
{
int menu = 0;
char item[10], item2[10];
node_p p;
while (menu != 9) {
printf("\n연결 리스트 연산\n\n");
printf("1. 정렬된 순서로 원소 삽입\n");
printf("2. 원소 탐색 후 다음 노드로 삽입\n");
printf("3. 원소 탐색 후 다음 노드 삭제\n");
printf("9. 종료\n\n");
printf("선택 : ");
scanf("%d", &menu);
switch(menu) {
case 1 :
printf("\n삽입할 원소값 : ");
scanf("%s", &item);
L = addNode(L, item);
printList(L);
break;
case 2 :
printf("\n탐색할 원소값 : ");
scanf("%s", &item);
printf("\n삽입할 원소값 : ");
scanf("%s", &item2);
p = searchNode(L, item);
L = insertNode(L, p, item2);
printList(L);
break;
case 3 :
printf("\n탐색할 원소값 : ");
scanf("%s", &item);
p = searchNode(L, item);
L = deleteNext(L, p);
printList(L);
break;
case 9 :
printf("\n프로그램 종료\n");
break;
default :
printf("\n잘못 선택함\n");
}
}
}
node_p addNode(node_p L, char *x)
{
node_p newNode;
node_p p;
node_p q;
newNode = (node_p)malloc(sizeof(struct listNode));
strcpy(newNode->data, x);
newNode->link = NULL;
if(L == NULL) {
L = newNode;
return L;
}
p = L;
if(strcmp(p->data, x) == 1) {
newNode->link = p;
L = newNode;
return L;
}
q = p->link;
while(q->link != NULL) {
if(strcmp(q->data, x) == -1) {
p = q;
q = q->link;
}
if(strcmp(q->data, x) == 1 || strcmp(q->data, x) == 0) {
newNode->link = q;
p->link = newNode;
return L;
}
}
q->link = newNode;
return L;
}
node_p searchNode(node_p L, char *x)
{
node_p p;
p = L;
while(p != NULL) {
if(!strcmp(p->data, x)) return p;
p = p->link;
}
return p;
}
node_p insertNode(node_p L, node_p p, char *x)
{
node_p newNode;
newNode = (node_p)malloc(sizeof(struct listNode));
strcpy(newNode->data, x);
newNode->link = NULL;
if(L == NULL || p == NULL) {
printf("원소가 존재하지 않음\n");
return L;
}
else if(p->link == NULL) {
p->link = newNode;
return L;
}
else {
newNode->link = p->link;
p->link = newNode;
return L;
}
}
node_p deleteNext(node_p L, node_p p)
{
node_p q;
if(L == NULL || p == NULL) {
printf("원소가 존재하지 않음\n");
return L;
}
else if(p->link == NULL) return L;
else {
q = p->link;
p->link = q->link;
free(q);
return L;
}
}