Skip to content

Instantly share code, notes, and snippets.

@dalcon10028
Last active May 27, 2020 00:57
Show Gist options
  • Save dalcon10028/a8406c171772a69f2accccaf57d2e8c1 to your computer and use it in GitHub Desktop.
Save dalcon10028/a8406c171772a69f2accccaf57d2e8c1 to your computer and use it in GitHub Desktop.
[ 자료구조 ] 연결리스트 2번 문제
/*
2. 다음과 같은 연결리스트를 생성하고 전체 노드의 데이터 값을 출력하시오.
head
-----> 1 -> 3 -> 5 -> 7 -> 9|NULL
*/
#include <stdio.h>
#include <stdlib.h>
// 노드 정의
struct _node {
int data;
struct _node *link;
};
typedef struct _node node;
void main(void) {
node *current, *tail, *head;
int i;
current = (node*) malloc(sizeof(node));
current->data = 1;
current->link = NULL;
head = tail = current;
// 1~10까지의 홀수 넣기
for(int i=3; i<10; i=i+2) {
// 새로운 주소 current로 할당 받기
current = (node*) malloc(sizeof(node));
if ( current == NULL ) { // 예외처리
printf("Memory Allocation Failed!\n");
exit(0);
}
current->data = i; // 새로운 데이터 넣기
current->link = NULL; // current가 현재 제일 끝이므로 NULL표시
tail->link = current; // 새로운 생성한노드(current)와 마지막 노드를 가리키는 tail과 연결
tail = current; // 마지막 노드를 가리키는 tail의 이동
}
current = head; // 현재위치 처음으로
for(int i=1; current != NULL; i++){
printf("%d번째 노드의 Data는 %d입니다.\n", i, current->data);
current = current->link;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment