fork(3) download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. struct Node
  5. {
  6. int n;
  7. struct Node *next;
  8. };
  9.  
  10. void showMenu();
  11. void printNodes(struct Node* p);
  12. void freeNodes(struct Node* p);
  13.  
  14. void main(){
  15. // 메인함수에서 사용할 기본 변수 선언
  16. int flag = 1;
  17. int input;
  18.  
  19. struct Node *head;//연결 리스트의 첫 원소를 저장할 포인터 변수 head
  20. struct Node *last;//마지막 원소의 주소를 저장할 last 변수
  21. struct Node *node;//추가될 노드의 주소를 임시로 저장할 포인터 변수 node
  22.  
  23. //아직 추가된 노드가 없기 때문에, Head 와 last 의 초기값을 NULL 로 설정
  24. head = NULL;
  25. last = NULL;
  26.  
  27. //사용자 입력이 0 이 될 때까지, 반복 수행
  28. while(flag){
  29. //메뉴를 출력 후, 사용자의 입력을 input 변수에 저장
  30. showMenu();
  31. scanf("%d", &input);
  32.  
  33. //사용자 입력이 0이면, flag 값을 0으로 바꾸고, while 반복문을 종료
  34. if(input ==0){
  35. flag = 0;
  36. }else{//사용자 입력이 0이 아니면, 노드를 연결 리스트에 추가
  37.  
  38. //Node 구조체를 동적 할당
  39. node = (struct Node*)malloc(sizeof(struct Node));
  40.  
  41. //생성된 Node 구조체에 값을 설정
  42. node->n = input;
  43. node->next = NULL;
  44.  
  45. //연결 리스트가 비어있을 경우, head에 생성된 node 의 주소를 저장
  46. if(head == NULL){
  47. head = node;
  48. }else{ //연결 리스트가 비어있지 않을 경우, 마지막 노드의 next에 생성된 node의 주소를 저장
  49. last->next=node;
  50. }
  51.  
  52. //연결 리스트에 추가된 node의 주소를 last에 저장
  53. last = node;
  54. }
  55. }
  56.  
  57. //연결 리스트에 저장된 값을 화면에 출력하고, 사용된 동적 메모리를 모두 해제
  58. printNodes(head);
  59. freeNodes(head);
  60. }
  61.  
  62. void showMenu(){
  63. printf("저장할 정수를 입력/종료:0 : ");
  64. }
  65.  
  66. void printNodes(struct Node* p){
  67. //p가 NULL 아닌 경우 = 마지막 노드가 아닌 경우
  68. while(p!=NULL){
  69. //노드에 저장된 값을 출력하고, 다음 노드로 이동
  70. printf("%d\n",p->n);
  71. p = p->next;
  72. }
  73. }
  74.  
  75. void freeNodes(struct Node* p){
  76. struct Node *temp;//다음 노드의 주소를 임시 저장할 temp 변수
  77. while(p!=NULL){//연결 리스트의 끝 까지 반복
  78. temp = p;//지울 노드를 임시변수에 저장
  79. p = p->next;//다음 노드로 이동
  80. free(temp);//임시변수에 저장된 이전 노드를 해제
  81. }
  82. }
Success #stdin #stdout 0s 9432KB
stdin
Standard input is empty
stdout
저장할 정수를 입력/종료:0 :