1 / 24

4. Application

4. Application. A list of award-winning pictures and their directors Three major functions Print instruction Build the list Process user inquiries Get the user’s choice Print the entire list Search for a requested year One other (important) function

rogelioj
Download Presentation

4. Application

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 4. Application • A list of award-winning pictures and their directors • Three major functions • Print instruction • Build the list • Process user inquiries • Get the user’s choice • Print the entire list • Search for a requested year • One other (important) function • A compare function to compare two years (keys) main AcademyAwards cmpYear printInstr buildList process getChoice printList search Data Structure

  2. 4. Application • Data Structure • File Name: academy.c (이후모든 구현은 이 한 파일에 추가) #include <stdio.h> #include <stdlib.h> #include <cType.h> #include "stdbool.h" #include "list.h" #define STR_MAX 41 //const short STR_MAX = 41; typedef struct { short year; char picture [STR_MAX]; char director[STR_MAX]; } PICTURE; [stdbool.h] #ifndef _STDBOOL_H #define _STDBOOL_H typedef int _Bool; #define bool _Bool #define true 1 #define false 0 #define __bool_true_false_are_defined 1 #endif Data Structure

  3. 4. Application • Data File • File Name: pictures.dat 1934 "It Happened One Night" "Frank Capra" 1932 "Cavalcade" "Frank Lloyd" 1939 "Gone With the Wind" "Victor Fleming" 1941 "How Green Was My Valley" "John Ford" 1938 "You Can't Take It With You" "Frank Capra" 1942 "Mrs. Miniver" "William Wyler" 1942 "Duplicate Movie" "ERROR" 1943 "Casablanca" "Michael Curtiz" 1945 "The Lost Weekend" "William Wyler" 1946 "The Best Years of Our Lives" "William Wyler" 1947 "Gentleman's Agreement" "Elia Kazan" 1950 "All About Eve" "Joseph L. Mankiewicz" 1953 "From Here To Eternity" "Fred Zinnemann" Data Structure

  4. 4. Application • Mainline for Academy Awards main void printInstr (void); LIST* buildList (void); void process (LIST* list); char getChoice (void); void printList (LIST* list); void search (LIST* list); int cmpYear (void* pYear1, void* pYear2); int main (void) { LIST* list; printInstr (); list = buildList (); process (list); printf("End Best Pictures\n" "Hope you found your favorite!\n"); return 0; } printInstr void printInstr (void) { printf("This program prints the …“ … … "the rest. Enjoy.\n"); return; } Data Structure

  5. 4. Application • Mainline for Academy Awards buildList (1/4) LIST* buildList (void) { FILE* fpData; LIST* list; short yearIn; int addResult; PICTURE* pPic; list = createList (cmpYear); if (!list) printf("\aCannot create list\n"), exit (100); fpData = fopen("pictures.dat", "r"); if (!fpData) printf("\aError opening input file\n"), exit (110); Data Structure

  6. 4. Application • Mainline for Academy Awards • int *fscanf( FILE *stream, const char *format, ...) • 인수 • FILE *stream  읽고자 하는 FILE 포인터 • const char *format  읽어 들일 데이터 서식 • ...  서식에 맞춘 변수 나열 • 반환 • 읽기에 성공했다면 읽어들인 항목 개수를 반환 • 실패나 오류가 발생하면 -1을 반환 • 위 예에서 "%hd"의 의미 • h: short • d: int (정수) • 참고: http://www.opengroup.org/onlinepubs/009695399/functions/scanf.html buildList (2/4) while (fscanf(fpData, " %hd", &yearIn) == 1) { pPic = (PICTURE*) malloc(sizeof(PICTURE)); if (!(pPic)) printf("\aOut of Memory in build list\n"), exit (100); pPic->year = yearIn; Data Structure

  7. 4. Application • Mainline for Academy Awards • "%40[^\"] %*c"의 의미 • %40[…] • [ ] 안에있는 것들로만 최대 40개의 글자를 읽음. 결과는 string 으로 처리한다 즉, 맨 마지막에 ‘\0’이 자동 할당 • %40[^\"] • "를 만날 때 까지 최대 40개의 글자를 읽음. 결과는 string 으로 처리한다 즉, 맨 마지막에 ‘\0’이 자동 할당 • [^…] 의의미  … 을만날 때 까지 • %*c • 입력 버퍼에 들어와 있는 " 글자를 무시하라는 뜻 buildList (3/4) while ((fgetc(fpData)) != '\t'); //\t 글자를 읽을 때 까지 loop while ((fgetc(fpData)) != '"') ; // " 글자를읽을 때 까지 loop fscanf(fpData, " %40[^\"] %*c", pPic->picture); while ((fgetc(fpData)) != '\t'); while ((fgetc(fpData)) != '"'); fscanf(fpData, " %40[^\"] %*c", pPic->director); Data Structure

  8. 4. Application • Mainline for Academy Awards • addNode 는 다음의 반환값을 가짐 (list.h 참고) • 0: Success • 1: Duplication • -1: heap overflow buildList (4/4) addResult = addNode (list, pPic); if (addResult != 0) if (addResult == -1) printf("Memory overflow adding movie\a\n"), exit (120); else printf("Duplicate year %hd not added\n\a", pPic->year); while (fgetc(fpData) != '\n'); //\n 글자를 읽을 때 까지 loop } return list; } Data Structure

  9. 4. Application • Mainline for Academy Awards Data Structure

  10. 4. Application • Mainline for Academy Awards process void process (LIST* list) { char choice; do { choice = getChoice (); switch (choice) { case 'P': printList (list); break; case 'S': search (list); case 'Q': break; } } while (choice != 'Q'); return; } Data Structure

  11. 4. Application • Mainline for Academy Awards getChoice char getChoice (void) { char choice; bool valid; printf("======== MENU ======= \n" ………….); do { scanf(" %c", &choice); choice = toupper(choice); switch (choice) { case 'S': case 'P': case 'Q': valid = true; break; default: valid = false; printf("\aInvalid choice\n" "Please try again: "); break; } } while (!valid); return choice; } Data Structure

  12. 4. Application • Mainline for Academy Awards • traverse 함수에서 두 번째 인자 (0, 1) 의의미 • 0  list 내의 pos 포인터 초기화 • 1  기존 pos 포인터의 그 다음 노드를 pos가 가리키도록 함 • "%hd %-40s %s\n"의의미 • %hd  short int 출력, %-40s  왼쪽정렬로 40개의 글자칸 확보하여 string 출력, %s  (왼쪽정렬로) string 출력 printList void printList (LIST* list) { PICTURE* pPic; if (listCount (list) == 0) printf("Sorry, nothing in list\n\a"); else { printf("\nBest Pictures List\n"); traverse (list, 0, (void**)&pPic); do { printf("%hd %-40s %s\n", pPic->year, pPic->picture, pPic->director); } while (traverse (list, 1, (void**)&pPic)); } printf("End of Best Pictures List\n\n"); } Data Structure

  13. 4. Application • Mainline for Academy Awards search void search (LIST* list) { short year; bool found; PICTURE pSrchArgu; PICTURE* pPic; printf("Enter a four digit year: "); scanf ("%hd", &year); pSrchArgu.year = year; found = searchList (list, &pSrchArgu, (void**)&pPic); if (found) printf("%hd %-40s %s\n", pPic->year, pPic->picture, pPic->director); else printf("Sorry, but %d is not available.\n", year); return; } Data Structure

  14. 4. Application • Mainline for Academy Awards cmpYear int cmpYear (void* pYear1, void* pYear2) { int result; short year1; short year2; year1 = ((PICTURE*)pYear1)->year; year2 = ((PICTURE*)pYear2)->year; if (year1 < year2) result = -1; else if (year1 > year2) result = +1; else result = 0; return result; } Data Structure

  15. 5. Complex Implementation • Circularly Linked Lists • Last node’s link points to the first node • Usually circularly linked lists are represented by “rear (last)” point instead of “head” point(Why?) Non-circularly linked list Circularly linked list Data Structure

  16. 5. Complex Implementation • Doubly Linked Lists • Each node has a pointer to both its successor and predecessor • 정의: 하나의 노드가 선행 노드와 후속 노드에 대한 두 개의 링크를 가지는 리스트 Singly linked list Doubly linked list Data Structure

  17. 5. Complex Implementation • Doubly Linked Lists • Insert node Data Structure

  18. 5. Complex Implementation • Doubly Linked Lists • Delete node Data Structure

  19. 5. Complex Implementation • Doubly Linked Lists 의 특징 및 장점 • 현재의 바로 이전 노드를 찾기가 쉽다. • 링크가 양방향이므로 양방향으로 검색이 가능 • Trade-off (타협, 균형) • Singly-Linked List vs. Doubly-Linked List • 삽입, 삭제의 시간 측면 • 메모리 사용 공간의 측면 • 프로그램 코딩의 양 측면 • Circularly and Doubly Linked List Data Structure

  20. 5. Complex Implementation • Multilinked Lists • Multilinked list  a list with two or more logical key sequences • The power (장점) of the multilinked list • The same set of data can be processed in multiple sequence • Ex) First 10 presidents of USA • 1st key: name of president • 2nd key: name of first lady Data Structure

  21. 5. Complex Implementation • Multilinked Lists • Ex) First 10 presidents of USA • 1st key: name of president • 2nd key: name of first lady • A list with just three elements • If we follow the president links, we traverse the list through… • Adams  Jefferson  Washington • If we follow the spouse links, we traverse the list through… • Custis  Skelton  Smith Data Structure

  22. 5. Complex Implementation • Deque (Double Ended Queue ,데크) -교재에서는 안나오지만 중요한 내용- • 특수한 형태의 큐로서 삽입 삭제가 Front (=Head)와 Rear에서 가해질 수 있도록 허용한 자료구조 • 스택과 큐의 성질을 종합한 순서 리스트 • 중요 연산 • AddLast( ) • AddFirst( ) • RemoveLast( ) • RemoveFirst( ) • 응용 예 • 화면 스크롤 • AddLast( ) • RemoveFirst( ) Deque • AddFirst( ) • RemoveLast( ) Data Structure

  23. Queue Operations DequeOperations 5. Complex Implementation • Deque (Double Ended Queue ,데크) • 데크를 사용한 큐 구현: • RemoveFirst( ), AddLast( ) 만을 사용 • 데크를 사용한 스택 구현: • RemoveFirst( ), AddFirst( )만을 사용 Stack Operations AddFirst() AddLast() RemoveFirst() RemoveLast() Data Structure

  24. 5. Complex Implementation • Deque에 대한 일련의 연산 수행 예

More Related