Presentation is loading. Please wait.

Presentation is loading. Please wait.

Data Structure1 4. Application A list of award-winning pictures and their directors Three major functions  Print instruction  Build the list  Process.

Similar presentations


Presentation on theme: "Data Structure1 4. Application A list of award-winning pictures and their directors Three major functions  Print instruction  Build the list  Process."— Presentation transcript:

1 Data Structure1 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) Academy Awards printInstrbuildListprocess cmpYear getChoiceprintListsearch main

2 Data Structure2 4. Application Data Structure File Name: academy.c ( 이후 모든 구현은 이 한 파일에 추가 ) #include #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; #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 [stdbool.h]

3 Data Structure3 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"

4 Data Structure4 4. Application Mainline for Academy Awards 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; } void printInstr (void) { printf("This program prints the …“ … "the rest. Enjoy.\n"); return; } main printInstr

5 Data Structure5 4. Application Mainline for Academy Awards 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); buildList (1/4)

6 Data Structure6 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 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; buildList (2/4)

7 Data Structure7 4. Application Mainline for Academy Awards "%40[^\"] %*c" 의 의미  %40[…] [ ] 안에 있는 것들로만 최대 40 개의 글자를 읽음. 결과는 string 으로 처리한다  즉, 맨 마지막에 ‘\0’ 이 자동 할당  %40[^\"] " 를 만날 때 까지 최대 40 개의 글자를 읽음. 결과는 string 으로 처리한다  즉, 맨 마지막에 ‘\0’ 이 자동 할당 [^…] 의 의미  … 을 만날 때 까지  %*c 입력 버퍼에 들어와 있는 " 글자를 무시하라는 뜻 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); buildList (3/4)

8 Data Structure8 4. Application Mainline for Academy Awards addNode 는 다음의 반환값을 가짐 (list.h 참고 )  0: Success  1: Duplication  -1: heap overflow 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; } buildList (4/4)

9 Data Structure9 4. Application Mainline for Academy Awards

10 Data Structure10 4. Application Mainline for Academy Awards 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; } process

11 Data Structure11 4. Application Mainline for Academy Awards 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; } getChoice

12 Data Structure12 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 출력 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"); } printList

13 Data Structure13 4. Application Mainline for Academy Awards 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; } search

14 Data Structure14 4. Application Mainline for Academy Awards 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; } cmpYear

15 Data Structure15 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

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

17 Data Structure17 5. Complex Implementation Doubly Linked Lists Insert node

18 Data Structure18 5. Complex Implementation Doubly Linked Lists Delete node

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

20 Data Structure20 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

21 Data Structure21 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

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

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

24 24 5. Complex Implementation Deque 에 대한 일련의 연산 수행 예 Deque 연산 Deque 내부 AddFirst(deque,3)(3) AddFirst(deque,5)(5, 3) RemoveFirst(deque)(3) AddLast(deque,7)(3, 7) RemoveFirst(deque)(7) RemoveLast(deque)() AddFirst(deque,9)(9) AddLast(deque,7)(9, 7) AddFirst(deque,3)(3, 9, 7) AddLast(deque,5)(3, 9, 7, 5) RemoveLast(deque)(3, 9, 7) RemoveFirst(deque)(9, 7)


Download ppt "Data Structure1 4. Application A list of award-winning pictures and their directors Three major functions  Print instruction  Build the list  Process."

Similar presentations


Ads by Google