상세 컨텐츠

본문 제목

C 언어 예제, 메모리 동적 할당 + 구조체와 노드 다루기

컴퓨터 관련/C 언어 예제

by 열정과 함께 2015. 1. 5. 19:51

본문

노드를 다뤄 보라고 하더라. 아래 코드는 세 개의 함수로 구성되어 있다.


make_node

insert_node

node_check


make_node 는 노드의 전체 초기 집합을 만든다. 초기값은 1, 2, 3, 4, ... 이 되도록 잡았다.

insert_node 는 노드 하나를 새로 만들고 이를 중간에 끼워넣는다.

node_check 는 작업이 잘 수행되었나 보기 위해 데이터를 출력해본다.


단, 맨 앞에 끼워넣는 것은 안 된다. 만드려니 조금 어려운 거 같아서 뺐다...... 끼워넣는 작업도 한 번 밖에 안된다. 여러번 끼우려면.....  너무 복잡해질 것 같아서 뺐다. 결과물은 아래와 같다.





코드는 아래와 같다.


#include <stdio.h>

#include <stdlib.h>

/* 노드를 새로 할당 / 노드를 원하는 위치에 삽입 */

struct Node

{

int data;

struct Node *nextNode;

};

struct Node make_node(struct Node *Node_arr, int *node_number);

struct Node insert_node(struct Node *Node_arr, int *insert_location);

int node_check(struct Node *Node_arr);

int main()

{

int node_number;

int insert_location;

struct Node *Node_arr;

printf("몇 개의 노드를 만들겠습니까? : ");

scanf("%d", &node_number);

Node_arr=(struct Node *)malloc(sizeof(struct Node)*node_number);

make_node(Node_arr, &node_number);

node_check(Node_arr);

printf("몇 번째 노드의 뒤에 삽입하겠습니까? : ");

scanf("%d", &insert_location);

insert_node(Node_arr, &insert_location);

node_check(Node_arr);

return 0;

}

int node_check(struct Node *Node_arr)

{

int i=0;

struct Node *location;

printf("데이터 값을 점검합니다. \n");

location=&Node_arr[0];

for(;;)

{

printf("Node_arr[%d].data = %d \n", i,Node_arr->data);

i++;

if(Node_arr->nextNode==NULL)

{

break;

}

else

{

Node_arr=Node_arr->nextNode;

}


}

printf("데이터 값 점검 끝 \n");

return 0;

}

struct Node make_node(struct Node *Node_arr, int *node_number)

{

int i;

for(i=0;i<*node_number-1;i++)

{

Node_arr[i].data=i+1;

Node_arr[i].nextNode=&Node_arr[i+1];

}

Node_arr[*node_number-1].data=*node_number;

Node_arr[*node_number-1].nextNode=NULL;

return *Node_arr;

}

struct Node insert_node(struct Node *Node_arr, int *insert_location)

{

int data_add;

struct Node *new_location;

printf("추가하려는 변수 data 의 값은 얼마입니까? : ");

scanf("%d", &data_add);

new_location=(struct Node *)malloc(sizeof(struct Node));

new_location->data=data_add;

if(insert_location==0)

{

printf("첫 번째에는 넣을 수 없습니다. \n");

}

else

{

Node_arr[*insert_location-1].nextNode=new_location;

new_location->nextNode=&Node_arr[*insert_location];

}

return *Node_arr;

}

관련글 더보기

댓글 영역