7.22.2017

자료구조 복습

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

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

void disp(node* move) {
        while (move != NULL) {
                printf("%d"move->data); //현재 move 위치
                move move->next; // 다음 노드로 한칸씩 이동
        }
        printf("\n");
}

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

void search_node(node* move) {
        int data;
        printf("찾으시는 데이터 입력 : ");
        scanf("%d", &data);
        while (move != NULL) {
                if (move->next->data == data) {
                        //찾는 데이터가 노드에 있을 경우
                        printf("%d \n", move->data);
                        printf("찾으시는 데이터가 있습니다.");
                        break;
                }
                move = move->next;
        //없을 경우, 그냥 종료
        }
}

void main() {
        //input 함수에 들어갈 때 마다
        //newnode 생성 후, 보내준 인자값
        //newnode->data에 대입
        node* head = (node*)malloc(sizeof(node));
        head->next = NULL;
        input(&head,10);
        input(&head,20);
        input(&head,30);
        disp(head->next);

        system("pause");
}

미로 만들기

#include <iostream>
#include <Windows.h>

using namespace std;

void main(){
        char arr[7][5] = {
                { ' ',' ',' ','*',' ' },
                { '*','*',' ','*',' ' },
                { ' ',' ',' ','*',' ' },
                { ' ','*',' ',' ',' ' },
                { ' ',' ','*',' ','*' },
                { ' ','*','*',' ',' ' },
                { ' ',' ','*',' ',' ' },
        };

        int x = 0, y = 0, i = 0, j = 0;
        char move;
        //위(w) : 행의 좌표 --
        //아래(s) : 행의 좌표 ++
        //왼쪽(a) : 열의 좌표 --
        //오른쪽(d) : 열의 좌표 ++

        //맵 밖으로 못 나가게 예외 처리
        //벽을 만났을 경우 위치 이동(x)

        while (true) {
                cout << "-----현재 좌표-----\n";
                cout << "x : " << x << " , y : " << y << endl;
                arr[x][y] = 'p';
                for (i = 0; i < sizeof(arr) / sizeof(arr[i]); i++) {
                        for (j = 0; j < sizeof(arr[i]); j++) {
                                cout << arr[i][j] << " ";
                        } cout << endl;
                }
                cin >> move;

                switch (move) {
                case 'w':
                        x--;
                        if (x<0 || arr[x][y] == '*') x++;
                        arr[x + 1][y] = ' ';
                        break;
                case 's':
                        x++;
                        if (x>6 || arr[x][y] == '*') x--;
                        arr[x - 1][y] = ' ';
                        break;
                case 'a':
                        y--;
                        if (y<0 || arr[x][y] == '*') y++;
                        arr[x][y+1] = ' ';
                        break;
                case 'd':
                        y++;
                        if (y>4 || arr[x][y] == '*') y--;
                        arr[x][y-1] = ' ';
                        break;
                default:
                        break;
                }
                system("cls"); //콘솔창 초기화
        }//end
}

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");
}

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

자료구조 BinarySearch

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

#pragma once

#ifndef SCORE_H
#define SCORE_H

typedef struct {
  int number;
  double score;
}Score;

Score DataSet[] = {
  1. 87.8,
  2. 69.9,
  3. 47.9,
  4. 56.6,
  5. 72.4,
  6. 67.3,
  7. 97.7,
  8. 99.8,
  9. 51.3,
  10. 12.5,
  11. 23.1,
  12. 42.7,
  13. 78.2,
  14. 55.4,
  15. 38.6,
  16. 82.4,
  17. 74.8,
  18. 90.0,
  19. 45.7,
  20. 74.2
};
#endif

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

#include <stdio.h>
#include <stdlib.h>
#include "Score.h"
//int* : 정수형 변수의 주소
//Score* : Score형 변수의 주소

Score* BinarySearch(Score ScoreList[], int Size, double Target) {
  int Left, Right, Mid;

  Left = 0;
  Right = Size - 1;

  while (Left <= Right) {
    Mid = (Left + Right) / 2;

    if (Target== ScoreList[Mid].score)
      return &(ScoreList[Mid]);
    else if (TargetScoreList[Mid].score)
      Left = Mid + 1;
    else 
      Right = Mid - 1;

    } return NULL;
}

int CompareScore(const  void * _elem1, const void _elem2) {
  Score* elem1 = (Score*)_elem1;
  Score* elem2 = (Score*)_elem2;

  if (elem1->score > elem2->score) return 1;
  else if (elem1->score < elem2->score) return -1;
  else return 0;
}

void main() {
        /*
        //1. BinarySearch 이용하기
        int Length = sizeof(DataSet) / sizeof(DataSet[0]);
        int i = 0;
        Score* found = NULL;

        //오름차순 정렬
        qsort((void*)DataSet, Length, sizeof(Score), CompareScore);

        //74.2 받은 학생 찾기
        found = BinarySearch(DataSet, Length, 74.2);
        printf("found : %d %f\n", found->number, found->score);


        //2. bSearch 함수 이용하기
  int Length = sizeof(DataSet) / sizeof(DataSet[0]);
  Scoretarget;
  Score* found = NULL;

  //오름차순 정렬
  qsort((void*)DataSet, Length, sizeof(Score), CompareScore);

  target.number = 0;
  target.score = 74.2;

  //74.2 받은 학생 찾기
  found = bsearch((void*)&target, (void*)DataSet, Length, 74.2);
  printf("found : %d %f\n", found->number, found->score);
}

7.19.2017

자료구조 전위법 - 배열

#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;
}

void ArrTransPose(int arr[], int Target) {
        int length = sizeof(arr) / sizeof(int);
        for (int i = 0; i < length; i++) {
                if (arr[i] == Target) {
                        int temp = arr[i];
                        arr[i] = arr[i - 1];
                        arr[i] = temp;
                        break;
                }
        }
}

void main() {
        int arr[] = { 1,3,5,7,9 };
        int length = sizeof(arr) / sizeof(int);
        for (int i = 0; i < length; i++){
                printf("arr[%d] : %d\n", i, arr[i]);
        }
        printf("\nAfter TransPost()...\n\n");
        ArrTransPose(arr, 5);

        for (int i = 0; i < length; i++)
                printf("arr[%d] : %d\n", i, arr[i]);
}

자료구조 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);
        }
}