Last active
June 3, 2020 04:49
-
-
Save dalcon10028/4f96a617340699f8f5e15ac7d3bf1734 to your computer and use it in GitHub Desktop.
연결 리스트 실습 1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <stdlib.h> | |
| // 노드 정의 | |
| struct _node { | |
| int data; // data | |
| struct _node *link; // link | |
| }; | |
| typedef struct _node node; | |
| int main() { | |
| node *current, *head=NULL; | |
| // 새로운 노드 생성을 위한 주소 할당 | |
| current = (node *) malloc(sizeof(node)); | |
| // 예외처리 | |
| if ( current == NULL ) { | |
| printf("Memory Allocation Error\n"); | |
| exit(1); | |
| } | |
| // 데이터 삽입 | |
| current->data = 10; | |
| current->link = NULL; | |
| // 현재 노드를 head로 가리키기 | |
| head = current; | |
| // 또 할당 받기 | |
| current = (node *) malloc(sizeof(node)); | |
| // 또 예외 처리 | |
| if ( current == NULL ) { | |
| printf("Memory Allocation Error\n"); | |
| exit(1); | |
| } | |
| // 또 데이터 삽입 | |
| current->data = 20; | |
| // 현재 노드를 마지막 노드로 만들기 (NULL 삽입) | |
| current->link = head->link; | |
| // head(첫 노드) 와 current (두 번째 노드)를 연결 | |
| head->link = current; | |
| printf("첫 번째 노드의 값 = %d\n",head->data); | |
| printf("두 번째 노드의 값 = %d\n",head->link->data); | |
| // 첫 노드의 메모리 반환 | |
| free(head); | |
| // 첫 노드가 바뀜 | |
| head = current; | |
| printf("삭제된 후 첫 번째 노드의 값 = %d\n",head->data); | |
| // 바뀐 첫 노드도 반환 | |
| free(head); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment