U E D R , A S I H C RSS

Linked List/숙제

~cpp 
// 영호가 작성 ㅋㅋㅋㅋㅋㅋㅋㅋ
/*
int a;          // 선언
a = 10;         // 정의
int b = 10;     // 선언&정의
*/



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

typedef struct _slist List;
typedef struct _slist{                  // 구조체
        int num;
        List *next;
        List *prev;
}List;


/*
struct _slist{
        int num;
        List *next;
        List *prev;
};


typedef로 'strucrt _slist'를 List로 정의한다.

즉, "List *aaa" == "struct _slist *aaa"
*/

#include "ExList.h"

void ShowList(List *plist)
{
        List *p;                // 구조체 선언.
        p=plist;
        while(p)
        {
                printf("%d\n",p->num);
                p=p->next;
        }
}

void main()
{
List *pList,*pNew,*pIns;        // struct _slist *pList, *pNew, *pIns;  구조체3개 선언

        pList=(List *)malloc(sizeof(List));     // malloc은 (List *)가 단위인 크기가 List인 메모리 공간을 생성하고 그 메모리 공간 첫 주소를 반환한다. 그 주소가 pList에 대입(정의)된다.
        pList->next=0;                  // 이 구조체가 처음 부분에 있다는 것을 표시한다. 0으로.
        pList->prev=0;                  // 이 구조체가 끝 부분에 있다는 것을 표시한다.
        pList->num=1;                   // 이 구조체 번호가 1번인 것을 표시한다.

        printf("root생성시\n");         // *pList를 root로 한다.
        ShowList(pList);

        pNew=(List *)malloc(sizeof(List));
        pList->next=pNew;               // pList의 다음 struct가 pNew인것을 표시.       pList ---> pNew
/*
pList->next 이것은 (*pList).next와 동일하다.
*/
        pNew->num=2;                    // 두번째 struct인 것을 표시한다.
        pNew->prev=pList;               // pNew의 이전 struct가 pList인것을 표시.       pList <--> pNew
        pNew->next=0;                   // pNew의 다음 struct가 없다는 것을 표시.

        printf("pNew생성시\n");
        ShowList(pList);

        pIns=(List *)malloc(sizeof(List));
        pIns->num=3;                    // 3번째 struct란 것을 표시.
        pIns->prev=pList;               // pIns를 pList와 pNew 사이에 집어 넣는다. (pList <-- pIns)
        pIns->next=pNew;                // pList <--> pNew, pIns ---> pNew
        pList->next=pIns;               // pList <--> pIns, pIns ---> pNew, pList <--- pNew (pList <--> pList, pList <--- pNew <--- pIns)
        pNew->prev=pIns;                // pList <--> pIns, pIns <--> pNew (pList <--> pIns <--> pNew)

        printf("pIns삽입시\n");
        ShowList(pList);

        pList->next=pNew;            // 알아서 해석해;;;
        pNew->prev=pList;
        free(pIns);                     // malloc함수로 만들어진 메모리중 쓸모 없는 메모리는 다시 반환되어야한다. (그렇지 않으면 메모리가 가득차서 컴퓨터가 멈춘다. ㅋㅋ)

        printf("pIns 삭제시\n");
        ShowList(pList);

        free(pNew);
        free(pList);
}
Valid XHTML 1.0! Valid CSS! powered by MoniWiki
last modified 2021-02-07 05:23:38
Processing time 0.0092 sec