본문 바로가기

공부방/IN지식

[요청] 링크드리스트(수정요청건)

sincerity*** 님이 요청하신 자료입니다.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct _node {
    char data;
    struct _node *next;
    struct _node *prev;   //구조체에 prev 가 추가되었죠.
};

struct _node *head;

int num(char n)
{
    struct _node *p, *tail;   
    p = (struct _node*)malloc(sizeof(struct _node));   
    p->data = n;
    p->next = NULL;   
    p->prev=NULL;
    if( head == NULL )
    {
        head = p;
    }
    else
    {
        tail = head;

        while( tail->next )
            tail = tail->next;
        tail->next = p;
        p->prev=tail;   //prev 가 가리킬곳역시 지적해줍니다. 전(前) 노드가 되겠죠.
    }
   
    return 0;
}
void ShowQ()
{
    struct _node *p = head;
    while(p->next)   // 노드의 맨 끝으로 이동합니다.
        p=p->next; 
   
    while( p ) {
        printf("%c",p->data);
        if( p->prev )   
            printf(" -> ");
        p= p->prev;  //끝에서 한칸씩 앞으로 옵니다.
    }
    printf("\n");
}

void main()
{
    char a;
    int b=1;
   
    while(b){
        scanf("%s",&a);
        if(a!='q')
            num(a);
        else{
            b=0;
            ShowQ();
        }
    }   
}