Last active
May 27, 2020 00:56
-
-
Save dalcon10028/69ddd2861c47b9e1db1eab58bc85922a to your computer and use it in GitHub Desktop.
[ 자료구조 ] 연결리스트 3번 문제
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
| /* | |
| 3. 위 연결리스트에서 각 노드의 데이터 값의 합을 출력하시오. | |
| 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, sum; | |
| 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; | |
| sum+=i; | |
| } | |
| printf("각 노드의 데이터값의 합은 %d입니다.\n",sum); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment