/*
* Author : Chang-Hwan Han
* Date : 2010.
* Description : double linked list
*/
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
typedef struct node
{
char* szName;
struct node* prevNode;
struct node* nextNode;
}Node;
Node* __insertNode(Node *pNode);
Node* __deleteNode(Node *pNode);
void __printNode(Node *pNode);
void __freeNode(Node *pNode);
void __freeNodeAll(Node *pNode);
void main()
{
Node *head = NULL;
char chInput;
while(1)
{
printf("1. insert\n");
printf("2. delete\n");
printf("3. print all\n");
printf("4. Exit\n");
printf("input menu : ");
scanf("%c", &chInput);
if(chInput=='1') head = __insertNode(head);
else if(chInput=='2') head = __deleteNode(head);
else if(chInput=='3') __printNode(head);
else if(chInput=='4') break;
else printf("input error\n");
fflush(stdin);
}
__freeNodeAll(head);
}
Node* __insertNode(Node *pNode)
{
Node *newNode, *curNode;
char szInputName[50];
printf("input node name : ");
fflush(stdin);
gets(szInputName);
newNode = (Node*)malloc(sizeof(Node));
newNode->szName = (char*)malloc((strlen(szInputName)+1) * sizeof(char));
strcpy(newNode->szName, szInputName);
newNode->nextNode = NULL;
newNode->prevNode = NULL;
if(pNode == NULL)
{
pNode = newNode;
pNode->nextNode = NULL;
pNode->prevNode = NULL;
}
else
{
curNode = pNode;
while(curNode->nextNode != NULL)
curNode = curNode->nextNode;
curNode->nextNode = newNode;
curNode->nextNode->prevNode = curNode;
}
return pNode;
}
Node* __deleteNode(Node *pNode)
{
Node *curNode;
char szInputName[50];
printf("delete node name : ");
fflush(stdin);
gets(szInputName);
curNode = pNode;
while(curNode != NULL)
{
if(strcmp(curNode->szName, szInputName) == 0)
{
if(curNode->prevNode == NULL && curNode->nextNode == NULL)
{
pNode = NULL;
}
else if(curNode->prevNode == NULL)
{
pNode = pNode->nextNode;
curNode->nextNode->prevNode = NULL;
}
else if(curNode->nextNode == NULL)
{
curNode->prevNode->nextNode = NULL;
}
else
{
curNode->nextNode->prevNode = curNode->prevNode;
curNode->prevNode->nextNode = curNode->nextNode;
}
__freeNode(curNode);
break;
}
curNode = curNode->nextNode;
}
if(curNode == NULL) printf("node not found\n");
return pNode;
}
void __printNode(Node *pNode)
{
while(pNode != NULL)
{
printf("%s -> ", pNode->szName);
pNode = pNode->nextNode;
}
printf("\n");
}
void __freeNode(Node *pNode)
{
free(pNode->szName);
free(pNode);
}
void __freeNodeAll(Node *pNode)
{
Node *node;
while(pNode != NULL)
{
node =pNode;
pNode = pNode->nextNode;
__freeNode(node);
}
}
|