자료구조 : 양방향 연결 리스트 1

ROK·2022년 10월 17일
0

열혈 자료구조

목록 보기
11/30

양방향 연결 리스트

앞서 원형, 단순 연결 리스트를 구현했었다.
이번에는 말그대로 양방향 앞 뒤의 노드가 서로 연결되어 있는 형태의 리스트를 만들어 보려고 한다.

처음 말로 들었을 때는 어려울 것이라고 생각했지만
막상 구현해보니 앞서 단순, 원형 연결 리스트를 충분히 이해해서 그런건지 모르겠지만
아주 쉽게 구현했다.

앞서 진행했던 리스트들의 연장이기 때문에 크게 설명할 부분은 없다


헤더파일

#ifndef __DB_LINKED_LIST_H__
#define __DB_LINKED_LIST_H__

#define TRUE 1
#define FALSE 0

typedef int Data;

typedef struct _node
{
   Data data;
   struct _node *next;
   struct _node *prev;
} Node;

typedef struct _DLinkedList
{
   Node *head;
   Node *cur;
   int numOfData;
} DBLinkedList;

typedef DBLinkedList List;

void ListInit(List *plist);
void LInsert(List *plist, Data data);

int LFirst(List *plist, Data *pdata);
int LNext(List *plist, Data *pdata);
int LPrevious(List *plist, Data *pdata);

int LCount(List *plist);

#endif

헤더파일에서 구조체 변수 Node를 정의하는 과정에 struct _node *prev가 추가된 것 말고는 크게 달라진 것이 없다.

소스파일

#include <stdio.h>
#include <stdlib.h>
#include "DBLinkedList.h"

void ListInit(List *plist)
{
   plist->head = NULL;
   plist->numOfData = 0;
}

void LInsert(List *plist, Data data)
{
   Node *newNode = (Node *)malloc(sizeof(Node));
   newNode->data = data;
   newNode->next = plist->head;

   if (plist->head != NULL)
   {
      plist->head->prev = newNode;
   }
   newNode->prev = NULL;

   plist->head = newNode;

   (plist->numOfData)++;
}

int LFirst(List *plist, Data *pdata)
{
   if (plist->head == NULL)
   {
      return FALSE;
   }

   plist->cur = plist->head;

   *pdata = plist->cur->data;

   return TRUE;
}

int LNext(List *plist, Data *pdata)
{
   if (plist->cur->next == NULL)
   {
      return FALSE;
   }

   plist->cur = plist->cur->next;

   *pdata = plist->cur->data;

   return TRUE;
}

int LPrevious(List *plist, Data *pdata)
{
   if (plist->cur->prev == NULL)
   {
      return FALSE;
   }

   plist->cur = plist->cur->prev;

   *pdata = plist->cur->data;

   return TRUE;
}

int LCount(List *plist)
{
   return (plist->numOfData);
}

메인파일

#include <stdio.h>
#include "DBLinkedList.h"

int main()
{
   // 초기화
   List list;
   int data;
   ListInit(&list);

   // 데이터 저장
   LInsert(&list, 1);
   LInsert(&list, 2);
   LInsert(&list, 3);
   LInsert(&list, 4);
   LInsert(&list, 5);
   LInsert(&list, 6);
   LInsert(&list, 7);
   LInsert(&list, 8);

   // 저장된 데이터 조회
   if (LFirst(&list, &data))
   {
      printf("%d ", data);

      // 오른쪽 노드로 이동하며 데이터 조회
      while (LNext(&list, &data))
      {
         printf("%d ", data);
      }
      
      printf("\n"); // 줄바꿈
      
      // 왼쪽 노드로 이동하며 데이터 조회
      while (LPrevious(&list, &data))
      {
         printf("%d ", data);
      }

      printf("\n\n");
   }

   return 0;
}

결과

8 7 6 5 4 3 2 1 
2 3 4 5 6 7 8
profile
하루에 집중하자

0개의 댓글