필요해서 추가하고 삭제 할때마다 해당하는 node의 index를 자동 정렬해주는 코드가 필요해서 작성해봤다.
나중에 수정해서 써봐야지.. ㅡㅡ;
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// simple linked list
// type define linked list
typedef struct _nodeObject
{
int nodeIdx;
char *string;
struct _nodeObject *Next;
} nodeObject;
// global define
nodeObject *gFileIdx;
// node index arrange
nodeObject* setNodeIdx(nodeObject *gNode)
{
int idx=0;
nodeObject *saveNode = NULL;
saveNode = gNode;
for(idx=0; gNode->Next != NULL; idx++)
{
gNode->nodeIdx = idx;
gNode = gNode->Next;
}
gNode->nodeIdx = idx;
gNode = saveNode;
return gNode;
}
// add node
nodeObject* AddNode(nodeObject *gNode, char *str)
{
nodeObject *newNode = NULL;
nodeObject *saveFirstNode = NULL;
// create node
if(gNode == NULL)
{
gNode = (nodeObject *)calloc(1, sizeof(nodeObject));
gNode->string = (char *)calloc(strlen(str)+1, sizeof(char));
gNode->string = str;
gNode->Next = NULL;
return gNode;
}
// add tail node
// save first node handle
saveFirstNode = gNode;
// make new node and set data
newNode = (nodeObject *)calloc(1, sizeof(nodeObject));
newNode->string = (char *)calloc(strlen(str)+1, sizeof(char));
newNode->string = str;
while( gNode->Next != NULL )
{
gNode = gNode->Next;
}
gNode->Next = newNode;
gNode = saveFirstNode;
gNode = setNodeIdx(gNode);
return gNode;
}
// delete node by index
nodeObject* deleteNode(nodeObject* gNode, int idx)
{
nodeObject *saveFirstNode = NULL;
nodeObject *beforeNode =NULL;
saveFirstNode = gNode;
while(idx != gNode->nodeIdx)
{
beforeNode = gNode;
gNode = gNode->Next;
}
beforeNode->Next = gNode->Next;
// free for delete node memory
free(gNode);
gNode = beforeNode;
gNode = saveFirstNode;
gNode = setNodeIdx(gNode);
return gNode;
}
int main( void )
{
gFileIdx = AddNode(gFileIdx, "hi1");
gFileIdx = AddNode(gFileIdx, "hi2");
gFileIdx = AddNode(gFileIdx, "hi3");
gFileIdx = AddNode(gFileIdx, "hi4");
gFileIdx = deleteNode(gFileIdx, 2);
gFileIdx = AddNode(gFileIdx, "hi5");
free(gFileIdx);
return 0;
}
'Code review' 카테고리의 다른 글
[WinApi]apiStart (0) | 2009.05.27 |
---|---|
[C]File merge (0) | 2009.05.27 |
[WinApi] 실행중인 프로세스 검사 - FindProcessName() (0) | 2009.02.01 |