본문 바로가기
1_ 맛있는프로그래밍

C - 알고리즘 - 더블링크드리스트(상)

by 준환이형님 2010. 6. 1.

링크드리스트에는 현재위치를 뿅! 뛰어넘는 부분이 있답니다.(start=start->next)  이런 부분이 오기 전에 포인터에 잠시 이전주소를 저장시켰다가 뿅 넘고 나서는 저장 시켜뒀던 이전 주소를 새로 만들어진 구조체에 연결 시켜줍니다. 언제든 돌아 갈 수 있도록 말이예요~ㅎ
 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct linked_list
{
 int data;
 linked_list *prev;
 linked_list *next; //새로나온 아이 (구조체 머리)
}link;

int main(void)
{
 int data_box[]={5,6,4,7,3,8,2,9,1,0,10};
 int length=sizeof data_box/ sizeof data_box[0];
 int num=NULL; 

 link* start;
 link* temp; //다음 만들어질 방
 link* temp_head; //이전 위치를 잠시 저장해 둘 포인터
 link* Front;
 
 temp = (link*)malloc(sizeof(link));
 start = (link*)malloc(sizeof(link));
 
 start->data=NULL;
 temp_head=start;

 Front=start;

 for(int i=0; i<length; i++)
 {
  start->data=data_box[i];

  start->next=temp;
  
  temp=(link*)malloc(sizeof(link));

  start->next=temp;

  temp_head=start; //미리 포인터에 현재위치를 저장

  start=start->next; // 넘겨주는 시점. 뿅뿅 

  start->prev=temp_head; //새로워진 위치의 -> 머리에 = 예전 위치를 매칭
 }
 start=Front;

for(int i=0; i<length; i++)
{
printf("%d ",start->data);
if(i==length-1){continue;} //마지막에는 꼬리를 달 이유가 없으므로
start=start->next;}printf("\n");

for(int i=0; i<length; i++){printf("%d ",start->data);start=start->prev;}printf("\n"); //다시 돌아오면서 출력