#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "doublylist.h"
DoublyList* createDoublyList()
{
DoublyList* pReturn = NULL;
pReturn = (DoublyList*) malloc(sizeof(DoublyList));
if(pReturn != NULL)
{
memset(pReturn, 0, sizeof(DoublyList));
pReturn->headerNode.pLLink = NULL;
pReturn->headerNode.pRLink = NULL;
}
else
{
printf("memory error, createDoublyList()\n");
return NULL;
}
return pReturn;
}
int addDLElement(DoublyList* pList, int position, DoublyListNode element)
{
int i = 0;
int ret = FALSE;
DoublyListNode* pPreNode = NULL;
DoublyListNode* pNewNode = NULL;
if(pList != NULL)
{
if(position >= 0 && position <= pList->currentElementCount)
{
pNewNode = (DoublyListNode*) malloc(sizeof(DoublyListNode));
if(pNewNode == NULL)
{
printf("error, memory, addDLElement()\n");
return ret;
}
*pNewNode = element;
pNewNode->pLLink = NULL;
pNewNode->pRLink = NULL;
pPreNode = &(pList->headerNode);
for(i=0; i<position; i++)
{
pPreNode = pPreNode->pRLink;
}
pNewNode->pLLink = pPreNode;
pNewNode->pRLink = pPreNode->pRLink;
pPreNode->pRLink = pNewNode;
pPreNode->pRLink->pLLink = pNewNode;
pList->currentElementCount++;
ret = TRUE;
}
else
{
printf("position error, addDLElement()\n");
}
}
else
{
printf("pList is NULL\n");
}
return NULL;
}
int removeDLElement(DoublyList* pList, int position)
{
int i = 0;
int ret = FALSE;
int arraycount = 0;
DoublyListNode* pDelNode = NULL;
DoublyListNode* pPreNode = NULL;
if(pList != NULL)
{
arraycount = getDoublyListLength(pList);
if(position >= 0 && position < arraycount)
{
pPreNode = &(pList->headerNode);
for(i = 0; i<position; i++)
{
pPreNode = pPreNode->pRLink;
}
pDelNode = pPreNode->pRLink;
pPreNode->pRLink = pDelNode->pRLink;
pDelNode->pRLink->pLLink = pPreNode;
free(pDelNode);
pList->currentElementCount--;
ret = TRUE;
}
else
{
printf("position error, removeDLElement()\n");
}
}
return ret;
}
void deleteDoublyList(DoublyList* pList)
{
if(pList!=NULL)
{
clearDoublyList(pList);
free(pList);
}
}
void clearDoublyList(DoublyList* pList)
{
if(pList!=NULL)
{
while(pList->currentElementCount>0)
{
removeDLElement(pList, 0);
}
}
}
int getDoublyListLength(DoublyList* pList)
{
int ret;
if(pList!=NULL)
{
ret = pList->currentElementCount;
}
return ret;
}
DoublyListNode* getDLElement(DoublyList* pList, int position)
{
DoublyListNode* pReturn = NULL;
DoublyListNode* pNode = NULL;
int i = 0;
if(pList!=NULL)
{
if(position >=0 && position < pList->currentElementCount)
{
pNode = pList->headerNode.pRLink;
for(i=0; i<position; i++)
{
pNode = pNode->pRLink;
}
pReturn = pNode;
}
else
{
printf("position error, getDLElement()\n");
}
}
return pReturn;
}
void displayDoublyList(DoublyList* pList)
{
int i = 0;
if(pList != NULL)
{
printf("현재 노드 갯수 : %d\n", pList->currentElementCount);
for(i = 0; i<pList->currentElementCount; i++)
{
printf("[%d] - %d\n", i, getDLElement(pList, i)->data);
}
}
else
{
printf("not existed element\n");
}
}