레이블이 #자료구조인 게시물을 표시합니다. 모든 게시물 표시
레이블이 #자료구조인 게시물을 표시합니다. 모든 게시물 표시

8.19.2017

LinkedList 자료구조

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

typedef struct Test {
        int data;
        struct Test* p; //주소를 담을 변수 생성
}test;

void main(){
        test* head = (test*)malloc(sizeof(test)); //시작위치

        test t1;
        test t2;
        test t3;

        printf("%d\n", &t1);
        printf("%d\n", &t2);
        printf("%d\n\n", &t3);


        t1.data = 10;
        t2.data = 20; //(*t1.p).data = 20;
        t3.data = 30;

        t1.p = &t2;
        t2.p = &t3;
        t3.p = NULL;

        printf("%d\n", t1.p);
        printf("%d\n", t2.p);
        printf("%d\n", t3.p);

}

============================================================================

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

typedef struct TEST {
        int data;
        struct TEST* next;
}test;

void main() {
        //연결리스트 : 주소를 연결해 놓은 집합체
        //                         마지막 노드의 next는 NULL
        //                         head는 시작위치를 알려줄 수 있게끔
        //                         데이터 X

        test* head = (test*)malloc(sizeof(test));
        head->next = NULL;

        test* new1 = (test*)malloc(sizeof(test));
        (*head).next = new1;
        new1->next = NULL;

        test* new2 = (test*)malloc(sizeof(test));
        new1->next = new2;
        new2->next = NULL;

        test* new3 = (test*)malloc(sizeof(test));
        new2->next = new3;
        new3->next = NULL;

        new1->data = 10;
        new2->data = 20;
        new3->data = 30;

        test* move = head->next;
        while (move != NULL) {
                printf("%d", move->data);
                move = move->next;
        }printf("\n"); // 출력
}

=============================================================================

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

typedef struct Test {
        int data;
        struct Test* next;
}test;

test* head;

void input(int data) {
        test* newnode = (test*)malloc(sizeof(test));
        newnode->data = data;
        newnode->next = head->next;
        head->next = newnode;
}

void del_node1() {
   test* move = head->next;

   printf("삭제할 데이터 입력 : "); int data;
   scanf("%d", &data);

   while (move != NULL) {
      if (move->next->data == data) {
         test* temp = move->next;
         move->next = move->next->next;
         free(temp);
         break;
      }
      move = move->next;
   }
}

void del_node2() {
        test* move = head->next; //삭제할 노드를 찾을 변수
        test* move2 = head; //삭제할 노드의 이전 노드

        printf("삭제할 데이터 입력 : "); int data;
        scanf("%d", &data);

        while (move != NULL) {
                if (move->data == data) {
                        move2->next = move->next;
                        free(move);
                        break;
                }
                move = move->next;
                move2 = move2->next;
        }
}

void main() {
        head = (test*)malloc(sizeof(test));
        head->next = NULL;

        input(10);
        input(20);
        input(30);
        input(40);
        input(50);
        del_node2();

        test* move = head->next;
        while (move != NULL) {
                printf("%d", move->data);
                move = move->next;
        }printf("\n"); // 출력
}

8.05.2017

08.05 creating character

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

typedef struct Character {
        char nickname[12];
        int strength, level, exp; //체력, 레벨, 경험치
}character;
character* c;

void create(int index) {
        c = (character*)realloc(c, sizeof(character) * (index+ 1));

        printf("Enter character's nickname.\n");
        scanf("%s", c[index].nickname);
        printf("Enter character's strength.\n");
        scanf("%d", &c[index].strength);
        printf("Enter character's level.\n");
        scanf("%d", &c[index].level);
        printf("Enter character's experience point.\n");
        scanf("%d", &c[index].exp);
}
void show(int index) {
        for (int i = 0; i < index; i++) {
                printf("About your character...\n");
                printf("nickname : %s \n", c[i].nickname);
                printf("strength : %d \n", c[i].strength);
                printf("level : %d \n", c[i].level);
                printf("experience point : %d \n", c[i].exp);
        }
}
void deleteCharacter(int index) {
        char name[20];
        printf("Which nickname do you want to erase?");
        scanf("%s", name);
        for (int i = 0; i < index; i++) {
                if (!strcmp(c[i].nickname, name));
                //strcmp (compare values) : if same -> 0
                // if different -> 1, -1
                for (int k = i; k < index- 1; k++) {
                        //앞으로 당겨주는 작업을 할 반복문
                        c[i] = c[i + 1];
                        c = (character*)realloc(c, sizeof(character)*(index- 1));
                }//end for(k)
                break; //더 이상 입력할 닉네임을 찾을 필요가 없기 때문
        }//end if

}
void main() {
        int input = 0, index = 0;

        c = (character*)malloc(sizeof(character));
        while (input != 4) {
                printf("[menu]\n1.Create your own Character 2.Show your character 3.Delete your character 4.End this program\n");
                scanf("%d", &input);
                if (input == 1) {
                        create(index);
                        index++;
                }
                else if (input == 2) show(index);
                else if (input == 3) {
                        deleteCharacter(index);
                        index--;
                }
        }
}

08.05. 문자입력, 출력, 종료

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

char* arr;
void input(int i) {
        arr = (char*)realloc(arr, sizeof(char) * i);

        while (getchar() != '\n');
        scanf("%c", &arr[i-1]);

}
void show(int n) {
        for (int i = 0; i < n-1; i++) {
                printf("%c", arr[i]);
        }
}
void main() {

        arr = (char*)malloc(sizeof(char) * 1);
        int a = 6, b = 1;
                while (a != 3) {
                        printf("[menu]\n1. 문자입력 2. 모든 문자 출력 3. 종료\n");
                        scanf("%d", &a);
                        if (a == 1) {
                                input(b);
                                b++;
                        }
                        else if (a == 2)show(b);
        }
}

0805 자료구조 복습

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

void main() {
        /*
        정적할당 : 고정되어있는 값만 사용
                     ex) int num, int arr[5];
        동적할당 : 계속해서 변하는 값
                           컴파일을 실행할 때 저장할 변수를 늘리거나 줄일 때 사용
                           #include <stdlib.h>
        할당 : malloc(), calloc()  //재할당 : realloc()
        */

        //(void*)malloc(바이트크기)
        int* p = (int*)malloc(sizeof(int) * 4);
        // malloc를 이용하여 4개짜리 배열
        // 생성 후, 포인터 변수 p 에 배열의 첫번쨰 인덱스의 주소(배열의 시작주소)를 대입해줬다.

        /*
        0번째 인덱스 = 10, 1 = 20, 2 = 30
        */


        /*int arr[5];
        int* p;
        */

        *p = 10;
        p[1] = 20;
        p[2] = 30;

        printf("%d %d %d \n", *(p + 0), p[1], p[2]);

        //calloc(개수, 사이즈);
        // c : clean
        // 값이 없을 경우엔 0으로 초기화
        int* c = (int*)calloc(4, sizeof(int));
        *&c[0] = 50;
        c[1] = 60;
        c[2] = 70;
        printf("%d %d %d \n", c[0], c[1], c[2]);
        printf("c : %d, m : %d \n", c[3], p[3]);

        //_msize() : 동적할당된 배열의 사이즈
        // sizeof : 정적할당된 변수

        printf("&dbyte \n", _msize(p)); //16byte
        printf("&dbyte \n", _msize(c)); //16byte

        //realloc(누구, 사이즈?);
        p = (int*)realloc(p, sizeof(int)* 5);
        //4개짜리 공간 -> 5개짜리 공간
        printf("%dbyte \n", _msize(p)); //20byte
        printf("%d %d %d \n", p[0], p[1], p[2]); //20byte


        /*
        *& : 서로 상쇄
        &* 상쇄(X)
        arr[0] == *p == *(p+0) == *&p[0] == p[0]
        arr[1] == *(p+1) == *&p[1] == p[1]
        */
        /*int num;
        int *p2 = &num;
        *p2 = 20;
        */

        // *p2 == num
        // p2가 가지고 있는 주소로 접근(num으로 이동)하여 20을 대입하겠다.
}

7.21.2017

자료구조 PriorityQueue

//PriorityQueue.h 헤더파일 만들기

#ifndef PRIORITYQUEUE_H
#define PRIORITYQUEUE_H

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

typedef int PriorityType;

typedef struct tagPQNode {
        PriorityType Priority;
        void* Data;
}PQNode;

typedef struct tagPriorityQueue {
        PQNode* Nodes;
        int Capacity;
        int UsedSize;
}PriorityQueue;

PriorityQueue* Create(int InitialSize);
void Destroy(PriorityQueue* PQ);
void Enqueue(PriorityQueuePQPQNode NewData);
void Dequeue(PriorityQueuePQPQNode* Root);
int GetParent(int index);
int GetLeftChild(int index);
void SwapNodes(PriorityQueuePQint Index1int Index2);
void PrintNode(PriorityQueuePQ);
int IsEmpty(PriorityQueuePQ);

#endif

================================================================================

#include "PriorityQueue.h"

PriorityQueue* Create(int InitialSize){
        PriorityQueue* NewPQ = (PriorityQueue*)malloc(sizeof(PriorityQueue));
        NewPQ ->Capacity = InitialSize;
        NewPQ ->UsedSize = 0;
        NewPQ ->Nodes = (PQNode*)malloc(sizeof(PQNode)*NewPQ ->Capacity);

        printf("size : %d\n"sizeof(PQNode));

        return NewPQ ;
}

void Destroy(PriorityQueuePQ){
        free(PQ->Nodes);
        free(PQ);
}

void Enqueue(PriorityQueuePQPQNode NewNode){
        int CurrentPosition = PQ->UsedSize;
        int ParentPosition = GetParent(CurrentPosition);

        if (PQ->UsedSize == PQ ->Capacity) {
                PQ->Capacity *= 2;
                PQ->Nodes = (PQNode*)realloc(PQ->Nodes, sizeof(PQNode)*PQ->Capacity);
        }
        PQ->Nodes[CurrentPosition] = NewNode;

        while (PQ->Nodes[CurrentPosition].Priority < PQ->Nodes[ParentPosition].Priority) {
                SwapNodes(PQ, CurrentPosition, ParentPosition);

                CurrentPosition = ParentPosition;
                ParentPosition = GetParent(CurrentPosition);
        }
        PQ->UsedSize++;
}

void Dequeue(PriorityQueuePQPQNodeRoot){
        int ParentPosition = 0;
        int LeftPosition = 0;
        int RightPosition = 0;

        memcpy(Root, &PQ->Nodes[0], sizeof(PQNode));
        memset(&PQ->Nodes[0], 0, sizeof(PQNode));
        PQ->UsedSize--;
        SwapNodes(PQ, 0, PQ->UsedSize);

        LeftPosition = GetLeftChild(0);
        RightPosition = LeftPosition + 1;
        while (1) {
                int SelectedChild = 0;
                //자식이 없는 경우
                if (LeftPosition >= PQ->UsedSize) break;

                //오른쪽에 자식이 없는 경우(왼쪽에만 있는 경우)
                if (RightPosition >= PQ->UsedSize)
                        SelectedChild = LeftPosition;
                else { //양쪽 모두 자식이 있는 경우
                        if (PQ->Nodes[LeftPosition].Priority > PQ->Nodes[RightPosition].Priority)
                                SelectedChild = RightPosition;
                        else SelectedChild = LeftPosition;
                }

                if (PQ->Nodes[ParentPosition].Priority > PQ->Nodes[SelectedChild].Priority) {
                        SwapNodes(PQ, ParentPosition, SelectedChild);
                ParentPosition = SelectedChild;
                }
                else {
                        break;
                }
                LeftPosition = GetLeftChild(ParentPosition);
                RightPosition = LeftPosition + 1;
}
        if (PQ->UsedSize < (PQ->Capacity) / 2) {
                PQ->Capacity /= 2;
        }
}

int GetParent(int index) {
        return (index - 1) / 2;
}

int GetLeftChild(int index){
        return (2 * index) + 1;
}

void SwapNodes(PriorityQueuePQint Index1int Index2){
        int CopySize = sizeof(PQNode);
        PQNode* Temp = (PQNode*)malloc(CopySize);
        memcpy(Temp, &PQ->Nodes[Index1], CopySize);
        memcpy(&PQ->Nodes[Index1], &PQ->Nodes[Index2], CopySize);
        memcpy(&PQ->Nodes[Index1], Temp, CopySize);
        free(Temp);
}

void PrintNode(PQNodeNode){
        printf("작업 명 : %s (우선순위:%d)\n"Node->Data, Node->Priority);
}

int IsEmpty(PriorityQueuePQ){
        return (PQ->UsedSize == 0);
}

void main() {
        PriorityQueue* PQ = Create(3);
        PQNode Popped;

        PQNode Nodes[7] = {
                {34,(void*)"코딩"},
                {12,(void*)"수업"},
                {87,(void*)"커피마시기"},
                {45,(void*)"문서작성"},
                {35,(void*)"디버깅"},
                {66,(void*)"이닦기"}
        };

        for (int i = 0; i < 6; i++) {
                Enqueue(PQ, Nodes[i]);
        }
        printf("큐에 남아 있는 작업의 수 : %d\n", PQ->UsedSize);

        while (!IsEmpty(PQ)) {
                Dequeue(PQ, &Popped);
                PrintNode(&Popped);
        }
}

자료구조 Heap

//Heap.h 헤더 파일을 만든다.

//힙에 가장 작은 데이터를 갖는 노드는 루트 노드이다.
//1. 힙에 새로운 노드를 삽입하는 연산
//2. 힙의 최소값을 삭제하는 연산

/*
힙에 새로운 노드 삽입
1. 힙의 최고 깊이, 최 우측에 새 노드를 추가한다. 물론 이때 완전 이진트리를 유지해야 한다.
2. 삽입한 노드를 부모 노드와 비교한다. 삽입한 노드가 부모 노드보다 크면 제 위치에 삽입된 것이므로 연산을 종료한다.
하지만 부모 노드보다 작으면 다음 단계로 진행한다.
3. 삽입한 노드가 부모 노드보다 작으면 부모 노드와 삽입한 노드의 위치를 서로 바꾼다. 바꾸고 나면 다시 2단계를 진행한다. */

/*힙의 최소값 삭제
1. 힙의 루트에 최고 깊이, 최 우측에 있던 노드를 루트노드로 옮겨온다.
이때 힙의 속성이 파괴된다. 이를 복원하기 위한 작업을 다음 단계에서부터 시작한다.

2. 옮겨온 노드의 양쪽 자식을 비교하여 작은쪽 자식과 위치를 교환한다. 
3. 옮겨온 노드가 더 이상 자식이 없는 리프 노드가 되거나, 양쪽 자식보다 작은 값을 갖는 경우에는 삭제 연산을 종료한다.
그렇지 않은 경우에는 2단계를 반복한다. 
*/

#ifndef HEAP_H
#define HEAP_H

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

typedef int ElementType;

typedef struct tagHeapNode {
        ElementType Data;
}HeapNode;

typedef struct tagHeap {
        HeapNode* Nodes;
        int Capacity;
        int UsedSize;
}Heap;

Heap* Create(int InitialSize);
void Destroy(HeapH);
void Insert(HeapHElementType NewData);
void DeleteMin(HeapH, HeapNode* Root);
int GetParent(int index);
int GetLeftChild(int index);
void SwapNodes(HeapHint Index1int Index2);
void PrintNodes(Heap*H);
#endif

====================================================================================

Heap* Create(int InitialSize){
        Heap* NewHeap = (Heap*)malloc(sizeof(Heap));
        NewHeap->Capacity = InitialSize;
        NewHeap->UsedSize = 0;
        NewHeap->Nodes = (HeapNode*)malloc(sizeof(HeapNode)*NewHeap->Capacity);

        printf("size : %d\n"sizeof(HeapNode));

        return NewHeap;
}

void Destroy(HeapH){
        free(H->Nodes);
        free(H);
}

void Insert(HeapHElementType NewData){
        int CurrentPosition = H->UsedSize;
        int ParentPosition = GetParent(CurrentPosition);

        if (H->UsedSize == H->Capacity) {
                H->Capacity *= 2;
                H->Nodes = (HeapNode*)realloc(H->Nodes, sizeof(HeapNode)*H->Capacity);
        }
        H->Nodes[CurrentPosition].Data = NewData;

        while (H->Nodes[CurrentPosition].Data < H->Nodes[ParentPosition].Data) {
                SwapNodes(H, CurrentPosition, ParentPosition);

                CurrentPosition = ParentPosition;
                ParentPosition = GetParent(CurrentPosition);
        }
        H->UsedSize++;
}

void DeleteMin(HeapHHeapNodeRoot){
        int ParentPosition = 0;
        int LeftPosition = 0;
        int RightPosition = 0;

        memcpy(Root, &H->Nodes[0],sizeof(HeapNode));
        memset(&H->Nodes[0], 0, sizeof(HeapNode));
        H->UsedSize--;
        SwapNodes(H, 0, H->UsedSize);

        LeftPosition = GetLeftChild(0);
        RightPosition = LeftPosition + 1;
        while (1) {
                int SelectedChild = 0;
                //자식이 없는 경우
                if (LeftPosition >= H->UsedSize) break;

  //오른쪽에 자식이 없는 경우(왼쪽에만 있는 경우)
                if (RightPosition >= H->UsedSize)
                        SelectedChild = LeftPosition;
  else { //양쪽 모두 자식이 있는 경우
                        if (H->Nodes[LeftPosition].Data > H->Nodes[RightPosition].Data)
                                SelectedChild = RightPosition;
                        else SelectedChild = LeftPosition;
                }

                if (H->Nodes[ParentPosition].Data > H->Nodes[SelectedChild].Data) {
                        SwapNodes(H, ParentPosition, SelectedChild);
                        ParentPosition = SelectedChild;
                }
                else {
                        break;
                }
                LeftPosition = GetLeftChild(ParentPosition);
                RightPosition = LeftPosition + 1;
        }
        if (H->UsedSize < (H->Capacity) / 2) {
                H->Capacity /= 2;
        }
}
int GetParent(int index){
        return (index - 1) / 2;
}

int GetLeftChild(int index){
        return (2 * index) + 1;
}

void SwapNodes(HeapHint Index1int Index2){
        int CopySize = sizeof(HeapNode);
        HeapNode* Temp = (HeapNode*)malloc(CopySize);
        memcpy(Temp, &H->Nodes[Index1], CopySize);
        memcpy(&H->Nodes[Index1], &H->Nodes[Index2], CopySize);
        memcpy(&H->Nodes[Index1], Temp, CopySize);
}

void PrintNodes(Heap*H){
        for (int i = 0; i < H->UsedSize; i++) {
                printf("%d"H->Nodes[i].Data);
        }
        printf("\n");
}

void main() {
        Heap* H = Create(3);
        HeapNode MinNode;

        Insert(H, 12);
        Insert(H, 87);
        Insert(H, 111);
        Insert(H, 34);
        Insert(H, 16);
        Insert(H, 75);

        PrintNodes(H);

        DeleteMin(H, &MinNode);
        PrintNodes(H);
        system("pause");
}

7.20.2017

자료구조 RedBlackTree

레드 블랙트리가 균형을 유지하는 비결
1. 모든 노드는 빨간색 아니면 검은색이다.
2. 루트 노드는 검은색이다.
3. 리프 노드는 검은색이다.
4. 빨간 노드의 자식들은 모두 검은색이다. 하지만 검은색 노드의 자식이 빨간색일 필요는 없다.
5. 루트 노드에서 모든 리프 노드 사이에 있는 검은색 노드의 수는 동일하다.

================================================================================

자료구조 BinarySearchTree

//BST.h 만들기
#pragma once
#ifndef BST_H
#define BST_H

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

typedef int ElementType;

typedef struct tagBSTNode {
        struct tagBSTNode* Left;
        struct tagBSTNode* Right;

        ElementType Data;
}BSTNode;

BSTNode* CreateNode(ElementType Data);
void DestroyNode(BSTNodeNode);
void DestroyTree(BSTNodeTree);

BSTNode* SearchNode(BSTNodeTreeElementType Target);
BSTNode* SearchMinNode(BSTNodeTree);
void InsertNode(BSTNodeTreeBSTNodeChild);
BSTNode* RemoveNode(BSTNodeTreeBSTNodeParentElementType Target);
void PrintInorderTree(BSTNodeNode);

#endif

===========================================================================
//.h 만들기

//왼쪽 자식 노드는 나보다 작고, 오른쪽 자식 노드는 나보다 크다.

#include "BST.h"

BSTNode* CreateNode(ElementType NewData) {
        BSTNode* NewNode = (BSTNode*)malloc(sizeof(BSTNode));
        NewNode->Data = NewData;
        NewNode->Left = NULL;
        NewNode->Right = NULL;

        return NewNode;
}

void DestroyNode(BSTNodeNode) {
        free(Node);
}

void DestroyTree(BSTNodeTree) {
        if (Tree->Right != NULL)
                DestroyTree(Tree->Left);
        if (Tree->Left != NULL)
                DestroyTree(Tree->Right);
        Tree->Left = NULL;
        Tree->Right = NULL;

        DestroyNode(Tree);
}

BSTNode* SearchNode(BSTNodeTreeElementType Target){
if (Tree == NULL)
return NULL;
if (Tree->Data == Target) {
return Tree;
}
else if (Tree->Data > Target) {
return SearchNode(Tree->Left, Target);
}
else return SearchNode(Tree->Right, Target);
}

BSTNode* SearchMinNode(BSTNodeTree){
        if (Tree == NULL)
                return NULL;
        if (Tree->Left == NULL)
                return Tree;
        else return SearchMinNode(Tree->Left);
}

void InsertNode(BSTNodeTreeBSTNodeChild){
        if (Tree->Data < Child->Data) {
                if (Tree->Right == NULL)
                        Tree->Right = Child;
                else InsertNode(Tree->Right, Child);
        }
        else if (Tree->Data > Child->Data) {
                if (Tree->Left == NULL)
                        Tree->Left = Child;
                else InsertNode(Tree->Left, Child);
        }
}

BSTNode* RemoveNode(BSTNodeTreeBSTNodeParentElementType Target){
        BSTNode* Removed = NULL;

        if (Tree->Data > Target)
                Removed = RemoveNode(Tree->Left, TreeTarget);
        else if (Tree->Data < Target)
                Removed = RemoveNode(Tree->Right, TreeTarget);
        else {
                Removed = Tree;

                //leaf 노드인 경우
                if (Tree->Left == NULL&& Tree->Right == NULL) {
                        if (Parent->Left == Tree)
                                Parent->Left = NULL;
                        else Parent->Right = NULL;
                }
                //양쪽 모두 자식이 있는 경우
                else {
                        if (Tree->Left != NULL && Tree->Right != NULL)
                        {
                                //오른쪽 트리의 최소값 노드를 찾아 제거한 뒤 현재의 노드에 위치시킨다.
                                BSTNode* MinNode = SearchMinNode(Tree->Right);
                                MinNode = RemoveNode(TreeNULL, MinNode->Data);
                                Tree->Data = MinNode->Data;
                        }
                        else {
                                //자식이 하나인 경우
                                BSTNode* Temp = NULL;
                                if (Tree->Left != NULL)
                                        Temp = Tree->Left;
                                else
                                        Temp = Tree->Right;
                                if (Parent->Left != Tree)
                                        Parent->Left = Temp;
                                else
                                        Parent->Right= Temp;
                        }
                }
        } return Removed;
}

void InorderPrintTree(BSTNodeNode){
        if (Node == NULLreturn;
        InorderPrintTree(Node->Left);
        printf(" %d"Node->Data);
        InorderPrintTree(Node->Right);
}

void main() {
        BSTNode* Tree = CreateNode(123);
        BSTNode* Node = NULL;

        InsertNode(Tree, CreateNode(22));
        InsertNode(Tree, CreateNode(9918));
        InsertNode(Tree, CreateNode(424));
        InsertNode(Tree, CreateNode(17));
        InsertNode(Tree, CreateNode(3));

        InsertNode(Tree, CreateNode(98));
        InsertNode(Tree, CreateNode(34));

        InsertNode(Tree, CreateNode(760));
        InsertNode(Tree, CreateNode(317));
        InsertNode(Tree, CreateNode(1));

        //트리 출력
        InorderPrintTree(Tree);
        printf("\n");

        //특정 노드 삭제
        printf("Removing 98...\n");

        Node = RemoveNode(Tree, NULL, 98);
        DestroyNode(Node);

        InorderPrintTree(Tree);
        printf("\n");

        //특정 노드 삽입
        printf("Inserting 111...\n");
        InsertNode(Tree, CreateNode(111));
        InorderPrintTree(Tree);
        printf("\n");

        system("pause");
}

===========================================================================
//출력

7.19.2017

자료구조 Node로 표현하기

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


typedef struct Node {
  int data;
        struct Node * next;

}Node ;
//노드의 생성/소멸
//노드 추가
//노드 탐색
//노드 삽입

Node * CreateNode(int NewData) {
        Node *NewNode = (Node *)malloc(sizeof(Node)); //현재 생성한 노드 메모리 할당
        NewNode->data = NewData//현재 생성한 노드에 data 대입
        NewNode->next = NULL//현재 생성한 노드의 next가 NULL을 참조
        return NewNode; //현재 생성한 노드의 주소값 반환
}

void DestroyNode(NodeNode) {
        free(Node);
}

void AppendNode(Node** HeadNodeNewNode) {
       //헤드노드가 NULL이라면 새로운 노드가 Head
        if ((*Head) == NULL) {
                *Head NewNode;
        }
        else {
                //tail을 찾아 NewNode를 연결함.
                Node*tail = (*Head);
                while (tail->next != NULL) {
                        tail = tail->next;
                }tail->next = NewNode;
        }
}

void InsertAfter(NodeCurrentNodeNewNode) {
        NewNode->next = Current->next;
        Current->next = NewNode;
}

void InsertNewHead(Node** HeadNodeNewHead) {
        if ((*Head) == NULL) {
                *Head NewHead;
        }
        else {
                NewHead->next = *Head;
                *HeadNewHead;
        }
}

void RemoveNode(Node** Head, Node* Remove) {
if (*Head == Remove) {
*Head = Remove->next;
}
else {
Node* Current = *Head;
while (Current != NULL && Current->next != Remove) {
Current = Current->next;
}
if (Current != NULL) {
Current->next = Remove->next;
}
}
}


Node* SequentialSearch(NodeHeadint Target) {
        Node* Current = Head;
        while (Current!=NULL && Current->data != Target) {
                Current = Current->next;
        } return Current;
}

//1. 전진이동법
Node* MoveToFront(Node** Headint Target) {
        Node* Current = *Head;
        Node* Match = NULL;
        Node* Previous = NULL;

        while (Current != NULL) {
                if (Current->data == Target) {
                        Match = Current;
                        if (Previous != NULL) {
                                //Current의 앞 노드와 다음 노드 연결
                                Previous->next = Current->next;

                                //Current를 리스트의 헤드로 옮기기
                                Current->next = (*Head);
                                (*Head) = Current;
                        }break;
                }
                else {
                        PPrevious = Previous;
                        Previous = Current;
                        Current = Current->next;
                }
        } return Match;
}

//2. 전위법
Node* TransPose(Node** Headint Target) {
        Node* Current = *Head;
        Node* Match = NULL;
        Node* Previous = NULL//이전 노드
        Node* PPrevious = NULL//이전 노드의 이전 노드


        while (Current != NULL) {
                if (Current->data == Target) {
                        Match = Current;
                        if (Previous != NULL) {
                                if (PPrevious != NULL)
                                        PPrevious->next = Current;
                                else (*Head) = Current;

                                Previous->next = Current->next;
                                Current->next = Previous;
                        }break;
                }
                else {
                        PPrevious = Previous;
                        Previous = Current;
                        Current = Current->next;
                }

        } return Match;
}

//3. 빈도 계수법

void main() {
        Node* List = NULL;
        Node* Match = NULL;
        Node* Current = NULL;
        int Count = 0;
        for (int i = 0; i < 5; i++) {
                NewNode = CreateNode(2 * i + 1);
                AppendNode(&List, NewNode);
        }
        Count = GetNodeCount(List);
        for (int i = 0; i < Count; i++) {
                Current = GetNodeAt(List, i);
                printf("List[%d] : %d\n", i, Current->data);
        }
        printf("After MoveToFront... \n\n");
        Current = MoveToFront(&List, 7);
        Count = GetNodeCount(List);
        for (int i = 0; i < Count; i++) {
                Current = GetNodeAt(List, i);
                printf("List[%d] : %d\n", i, Current->data);
        }
}