앞서 기본적인 연결리스트를 구현해봤다 링크
앞에 단순 연결리스트는 int 자료형 데이터만 저장했지만, 더 다양한 데이터를 저장할 수 있다.
그래서 이번엔 구조체 변수 주소 값을 저장해보자
구조체
typedef struct _point
{
int xpos;
int ypos;
} Point;
구조체 Point 관련 함수들의 선언
#ifndef __POINT_H__
#define __POINT_H__
typedef struct _point
{
int xpos;
int ypos;
} Point;
void SetPointPos(Point *ppos, int xpos, int ypos); // xpos, ypos 값 설정
void ShowPointPos(Point *ppos); // xpos, ypos 값 출력
int PointComp(Point *pos1, Point *pos2); // 두 Point 변수 비교
#endif
구조체 Point 관련 함수들의 정의
#include <stdio.h>
#include "Point.h"
void SetPointPos(Point *ppos, int xpos, int ypos)
{
ppos->xpos = xpos;
ppos->ypos = ypos;
}
void ShowPointPos(Point *ppos)
{
printf("[%d, %d] \n", ppos->xpos, ppos->ypos);
}
int PointComp(Point *pos1, Point *pos2)
{
if (pos1->xpos == pos2->xpos && pos1->ypos == pos2->ypos)
{
return 0;
}
else if (pos1->xpos == pos2->xpos)
{
return 1;
}
else if (pos1->ypos == pos2->ypos)
{
return 2;
}
else
{
return -1;
}
}
#include <stdio.h>
#include <stdlib.h>
#include "ArrayList.h"
#include "Point.h"
int main()
{
List list;
Point CompPos;
Point *ppos;
ListInit(&list);
// 데이터 저장
ppos = (Point *)malloc(sizeof(Point));
SetPointPos(ppos, 2, 1);
LInsert(&list, ppos);
ppos = (Point *)malloc(sizeof(Point));
SetPointPos(ppos, 2, 2);
LInsert(&list, ppos);
ppos = (Point *)malloc(sizeof(Point));
SetPointPos(ppos, 3, 1);
LInsert(&list, ppos);
ppos = (Point *)malloc(sizeof(Point));
SetPointPos(ppos, 3, 2);
LInsert(&list, ppos);
// 데이터 출력 확인하기
printf("현재 데이터의 수 : %d \n", LCount(&list));
if (LFirst(&list, &ppos))
{
ShowPointPos(ppos);
while (LNext(&list, &ppos))
{
ShowPointPos(ppos);
}
}
printf("\n");
// 데이터 삭제 xpos == 2인 데이터 삭제
CompPos.xpos = 2;
CompPos.ypos = 0;
if (LFirst(&list, &ppos))
{
if (PointComp(ppos, &CompPos) == 1)
{
ppos = LRemove(&list);
free(ppos);
}
while (LNext(&list, &ppos))
{
if (PointComp(ppos, &CompPos) == 1)
{
ppos = LRemove(&list);
free(ppos);
}
}
}
// 삭제 후 남은 데이터 출력
printf("현재 데이터의 수 : %d \n", LCount(&list));
if (LFirst(&list, &ppos))
{
ShowPointPos(ppos);
while (LNext(&list, &ppos))
{
ShowPointPos(ppos);
}
}
printf("\n");
return 0;
}
현재 데이터의 수 : 4
[2, 1]
[2, 2]
[3, 1]
[3, 2]
현재 데이터의 수 : 2
[3, 1]
[3, 2]