Copyright 2000-2010 Networking Laboratory C programming and Data Structures Overview T. H. Cormen, C. E. Leiserson and R. L. Rivest Introduction to Algorithms,

Slides:



Advertisements
Similar presentations
Stacks, Queues, and Linked Lists
Advertisements

DATA STRUCTURES USING C++ Chapter 5
Chapter 3 – Lists A list is just what the name implies, a finite, ordered sequence of items. Order indicates each item has a position. A list of size 0.
Data Structure Lecture-3 Prepared by: Shipra Shukla Assistant Professor Kaziranga University.
Templates in C++ Template function in C++ makes it easier to reuse classes and functions. A template can be viewed as a variable that can be instantiated.
CS Data Structures ( 資料結構 ) Chapter 3: Stacks and Queues Spring 2012.
Review of Stacks and Queues Dr. Yingwu Zhu. Our Focus Only link-list based implementation of Stack class Won’t talk about different implementations of.
Data Structure (Part I) Stacks and Queues. Introduction to Stack An stack is a ordered list in which insertion and deletions are made at one end. –The.
Data Structures (Second Part) Lecture 3 : Array, Linked List, Stack & Queue Bong-Soo Sohn Assistant Professor School of Computer Science and Engineering.
 A queue is a waiting line…….  It’s in daily life:-  A line of persons waiting to check out at a supermarket.  A line of persons waiting.
CSCE 3110 Data Structures & Algorithm Analysis Queues Reading: Chap. 3 Weiss.
1 Queues and Lists. QUEUES Very similar to stacks The only difference between them is in the order in which elements are processed. A stack uses a last-in/first-out.
Data Structure Dr. Mohamed Khafagy.
Linked Lists Compiled by Dr. Mohammad Alhawarat CHAPTER 04.
Stack and Queue Dr. Bernard Chen Ph.D. University of Central Arkansas.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
Stacks CS-240 Dick Steflik. Stacks Last In, First Out operation - LIFO As items are added they are chronologically ordered, items are removed in reverse.
CS Data Structures Chapter 3 Stacks and Queues.
Chapter 4 Linked Lists. © 2005 Pearson Addison-Wesley. All rights reserved4-2 Preliminaries Options for implementing an ADT List –Array has a fixed size.
C++ Programming: Program Design Including Data Structures, Fifth Edition Chapter 17: Linked Lists.
CS Data Structures Chapter 4 Lists.
Chapter 3 Stacks and Queues  The Stack Abstract Data Type  The Queue Abstract Data Type  A Mazing Problem  Evaluation of Expressions.
Data Structures Using C++ 2E
Data Structures Using C++ 2E Chapter 7 Stacks. Data Structures Using C++ 2E2 Objectives Learn about stacks Examine various stack operations Learn how.
Review 1 Introduction Representation of Linear Array In Memory Operations on linear Arrays Traverse Insert Delete Example.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Custom Templatized Data Structures.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.
Adapted from instructor resources Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights.
Comp 245 Data Structures Linked Lists. An Array Based List Usually is statically allocated; may not use memory efficiently Direct access to data; faster.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 18: Stacks and Queues (part 3)
1 CSE 1342 Programming Concepts Lists. 2 Basic Terminology A list is a finite sequence of zero or more elements. –For example, (1,3,5,7) is a list of.
1 Stacks and Queues Based on D.S. Malik, Java Programming: Program Design Including Data Structures.
Data Structure in C Transparency No. 4-1 Copyright(c) 1997, Sungkyunkwan University Chapter #4: LISTS Fundamentals of Data Structure in C Horowitz, Sahni.
 Array ◦ sequential representation ◦ some operation can be very time-consuming (data movement) ◦ size of data must be predefined ◦ static storage allocation.
Lists, Stacks and Queues in C Yang Zhengwei CSCI2100B Data Structures Tutorial 4.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
1 Linked-list, stack and queue. 2 Outline Abstract Data Type (ADT)‏ Linked list Stack Queue.
Review of Stacks and Queues Dr. Yingwu Zhu. How does a Stack Work? Last-in-First-out (LIFO) data structure Adding an item Push operation Removing an item.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
Copyright © 2012 Pearson Education, Inc. Chapter 17: Linked Lists.
Copyright Networking Laboratory Chapter 4. LISTS Horowitz, Sahni, and Anderson-Freed Fundamentals of Data Structures in C, 2nd Edition Computer.
Chapter 12 Structure and ADTs 프로그래밍 기초와 실습. Chapter 12 Structure and ADTs 2 Contents  Declaring Structures  Accessing a Member  Operator Precedence.
APS105 Lists. Structures Arrays allow a collection of elements –All of the same type How to collect elements of different types? –Structures; in C: struct.
12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 9 An Introduction.
Data Structures. Abstract Data Type A collection of related data is known as an abstract data type (ADT) Data Structure = ADT + Collection of functions.
Abstract Data Types and Stacks CSE 2320 – Algorithms and Data Structures Vassilis Athitsos University of Texas at Arlington 1.
2005MEE Software Engineering Lecture 7 –Stacks, Queues.
1 Queues and Lists. QUEUES Very similar to stacks The only difference between them is in the order in which elements are processed. A stack uses a last-in/first-out.
Chapter 17: Linked Lists. Objectives In this chapter, you will: – Learn about linked lists – Learn the basic properties of linked lists – Explore insertion.
1 Midterm 1 on Friday February 12 Closed book, closed notes No computer can be used 50 minutes 4 questions Write a function Write program fragment Explain.
Data Structure & Algorithms
STACKS AND QUEUES.
◦ A one-dimensional array in C is declared implicitly by appending brackets to the name of a variable int list[5], *plist[5]; ◦ arrays start at index.
© Oxford University Press All rights reserved. Data Structures Using C, 2e Reema Thareja.
Copyright © 2012 Pearson Education, Inc. Chapter 17: Linked Lists.
Chapter 3 Lists, Stacks, Queues. Abstract Data Types A set of items – Just items, not data types, nothing related to programming code A set of operations.
STACKS & QUEUES for CLASS XII ( C++).
Data Structure Interview Question and Answers
Data Structures and Algorithms
Dr. Bernard Chen Ph.D. University of Central Arkansas
Chapter 4 Linked Lists.
Linked lists.
Stack and Queue APURBO DATTA.
EEE2108: Programming for Engineers Chapter 4. Linked Lists
CSCE 3110 Data Structures & Algorithm Analysis
Stacks and Queues The Stack abstract data type
Data Structures and Algorithms
Linked lists.
Presentation transcript:

Copyright Networking Laboratory C programming and Data Structures Overview T. H. Cormen, C. E. Leiserson and R. L. Rivest Introduction to Algorithms, 2nd Edition, MIT Press, 2001 Sungkyunkwan University Hyunseung Choo

Algorithms Contents Functions  Invocations Function  Function Definitions Return statements  Function Prototypes  Call by value and call by reference Recursions  Recursive Call  Examples Structures  Struct Declaration  Structure Tag  Compatible Structure  Memory Allocation  Accessing a Member Pointers  Pointer Variable  Passing Pointers to Functions  Exercise Problem Networking Laboratory 2/78

Algorithms Functions Networking Laboratory 3/78

Algorithms Invocations Function (1/3) Function  C 프로그램은 하나 이상의 Function 들로 구성  모든 c-program 은 반드시 한 개의 main() Function 을 포함  반복되는 codes 의 경우 function 으로 정의하여 필요 시 마다 그 function 을 호출하여 사용 함으로서 simplicity 의 향상  Function 의 종류  Library functions : System 이 제공하는 Predefined-Functions  User-defined functions : Programmer 에 의해 작성된 Functions  Function Invocation  Function 의 호출 : Function_name() 의 형식으로 사용.  Function 의 종료 : Function 을 Call 한 곳으로 제어 권의 이동 Networking Laboratory 4/78

Algorithms Invocations Function (2/3) Networking Laboratory 5/78

Algorithms Invocations Function (3/3) Networking Laboratory 6/78

Algorithms Function Definitions (1/2) Function 이 호출되기 전 반드시 해당 Function 을 다음 형식 으로 정의해야 한다. Networking Laboratory 7/78

Algorithms Function Definitions (2/2) Parameter Type List  Function 호출 시 전달되는 arguments 에 대응되는 순서와 data types 을 지정  Function body 내에서 identifier 로 사용될 수 있다 Return type  Function 종료될 때 return statement 에 의해 전달되는 value 의 type.  Default type : integer type 으로, 생략 시 자동 integer 로 간주  void type : Return Value 가 없는 경우 void 로 지정 Networking Laboratory 8/78

Algorithms The Return Statement Function 의 실행 종료, 호출한 곳으로 control 을 이전하는 statement 생략 시는 function body 끝의 ‘}’ 를 만났을 때 자동 return 복수개의 return 문 사용 가능  단, 하나의 Function 에서 두 개의 값을 동시에 return 할 수 없음 Networking Laboratory 9/78

Algorithms The Return Value Networking Laboratory 10/78

Algorithms Function Prototypes (1/2) Function 사용을 위해 호출 전에 반드시 필요한 Function 선 언문 prototype 이 생략 가능한 경우  모든 조건이 default 인 경우 생략 가능 : return value 의 type 과 argument 의 type 이 integer 인 경우 생략 가능  function 이 main() function 전에 정의 된 경우 선언 형식  return-type function_name (parameter type list); Networking Laboratory 11/78

Algorithms Function Prototypes (2/2) Argument 와 parameter 의 type 이 일치하지 않는 경우 function prototype 에서 지정된 type 으로 convert 됨. Networking Laboratory 12/78

Algorithms Function Definition Order 한 개의 file 로 작성된 program 의 일반적 순서 1. #include, #define statements 2. Enumeration types and typedef 3. struct definition 4. Function Prototypes 5. main() Function 6 Function Definitions Networking Laboratory 13/78

Algorithms main( ) 안에서의 Function Definition Networking Laboratory 14/78

Algorithms Developing Large Program (1/2) 대규모 Program 의 경우, 여러 ~.h 파일과 ~.c 파일로 나누어 작성할 수 있다. Team 에 의한 작업분담이 용이해진다. 프로그램이 변경될 때마다 변경된 ~.c 파일만을 compile 함 으로서 시간 절약 가능 Networking Laboratory 15/78

Algorithms Developing Large Program (2/2) Networking Laboratory 16/78

Algorithms Call by Value and Call by Reference Call-by-Value  Function Invocation 이 일어나면, argument 의 value 를 전달받기 위 한 parameter 를 위해 메모리영역이 새로 생기며 argument 의 값이 새 영역에 copy 된다.  Function Invocation 의 parameter 를 identifier 로 사용하여 그 값을 function 내에서 변경한 경우에도 다른 memory 영역을 사용함으로써 실제 argument 의 값은 변경되지 않는다 Call-by-Reference  Function Invocation 이 일어나면 argument 의 address 를 전달한다.  실제 값의 address 를 변경하기 때문에 그 값을 function 내에서 변경 한 경우 실제 argument 값이 변경된다. Networking Laboratory 17/78

Algorithms Example of Call by Value Networking Laboratory 18/78

Algorithms Example of Call by Reference Networking Laboratory 19/78

Algorithms Recursions Networking Laboratory 20/78

Algorithms Recursive Call 어떤 함수가 자기 자신을 호출하는 것 Networking Laboratory 21/78

Algorithms Factorial 을 구하는 예제 Networking Laboratory 22/78

Algorithms Array 의 평균을 구하는 예제 Networking Laboratory 23/78

Algorithms Drawing Patterns on the Screen (1/2) 제곱근을 구하는 예제 Networking Laboratory 24/78

Algorithms Drawing Patterns on the Screen (2/2) 역순으로 문자를 출력하는 예제  입력 받은 문장의 문자들을 역순으로 출력한다. Networking Laboratory 25/78

Algorithms Structures Networking Laboratory 26/78

Algorithms Array 와 structure 의 차이점 array  Array 의 모든 element 는 같은 type 이여야 한다.  Index 를 사용하여 각 element 를 access 한다. structure  다른 type 의 element 로 구성 될 수 있다 있다.  각 element 는 name 을 갖는다.  Name 에 의해 각 element 를 access 한다. Networking Laboratory 27/78

Algorithms Struct Declaration Struct Declaration Collection of members(/elements) Networking Laboratory 28/78

Algorithms Structure Tag 정의 되는 특정 structure 를 지정하기 위한 name 한 번 structure tag 인 part 가 정의되면, 이제 tag 를 사용하여 같은 structure type 으로 선언할 수 있다. Networking Laboratory 29/78

Algorithms Structure Tag 와 변수 동시 선언 structure tag 를 이용하여 선언된 변수는 같은 structure type Networking Laboratory 30/78

Algorithms Compatible Structure (1/2) 같은 type 의 structure variable 이면 서로 assign 가능 compatible types 의 조건  Structure 정의와 동시에 선언되는 모든 variables  같은 type 의 structure 즉 같은 tag 에 의해 선언된 모든 variables Networking Laboratory 31/78

Algorithms Compatible Structure (2/2) compatible type 이 아닐 경우 =, ==, != 불가능 Networking Laboratory 32/78

Algorithms Memory Allocation Structure 로 선언된 데이터 type 은 각 member 들이 메모리 내에 순차적으로 할당된다. part1 의 base address 가 200 이고, integer size 가 4byte 라 가정하면, 오른쪽 그림과 같이 메모리가 할당됨 Networking Laboratory 33/78

Algorithms Accessing a Member (1/3) struct member operator ‘.’  Structure 의 각 member 를 access 하기 위해 ‘.’ 를 사용한다. Networking Laboratory 34/78

Algorithms Accessing a Member (2/3) member operation Networking Laboratory 35/78

Algorithms Accessing a Member (3/3) structure pointer Networking Laboratory 36/78

Algorithms Structures as Argument call-by-value 로 struct 가 copy 되어 사용 된다. Networking Laboratory 37/78

Algorithms Struct Pointer 사용 (1/2) call-by-reference 로 struct 의 address 를 전달한다. Networking Laboratory 38/78

Algorithms Struct Pointer 사용 (2/2) Networking Laboratory 39/78

Algorithms The Use of typedef (1/2) data type 의 name 을 재 정의 하기 위해 사용 readability 의 증가 Networking Laboratory 40/78

Algorithms The Use of typedef (2/2) typedef 를 사용, struct type 을 새로운 type 으로 선언 Networking Laboratory 41/78

Algorithms Pointers Networking Laboratory 42/78

Algorithms Pointer Variable 포인터 변수는 변수명은 같으나 변수선언을 할 때 * 연산자 를 사용한다.  int *a; → int 형 포인터 포인터변수는 타입에 상관없이 4 바이트다. Networking Laboratory 43/78

Algorithms Passing Pointers to Functions (1/4) 포인터를 argument 로 하는 함수 예제 Networking Laboratory 44/78

Algorithms Passing Pointers to Functions (2/4) 포인터를 argument 로 하는 함수 예제 Networking Laboratory 45/78

Algorithms Passing Pointers to Functions (3/4) 포인터를 argument 로 하는 함수 예제 Networking Laboratory 46/78

Algorithms Passing Pointers to Functions (4/4) 포인터를 argument 로 하는 함수 사용시 유의점 Networking Laboratory 47/78

Algorithms Exercise Problem pointer 의 주소 할당 문제 Networking Laboratory 48/78

Algorithms Approaches pointer 의 예제 Networking Laboratory 49/78

Copyright Networking Laboratory Data Structures Overview Sungkyunkwan University Hyunseung Choo

Algorithms Contents Arrays  Arrays  Representation of Multidimensional Arrays Stacks and Queues  Stack Abstract Data Type  Queue Abstract Data Type  Circular Queues Lists  Singly Linked Lists  Doubly Linked Lists Networking Laboratory 51/78

Algorithms Arrays Networking Laboratory 52/78

Algorithms Arrays (1/2) An array is a set of pairs,, such that each index that is defined has a value associated with it A consecutive set of memory locations in C Logical order is the same as physical order int list[5], *plist[5]; /* arrays start at index 0 in C */ - integers: list[0],..., list[4] - int ptrs: plist[0],..., plist[4] Networking Laboratory 53/78

Algorithms Arrays (2/2) Variable Memory Address list[0]base address =  list[1]+ sizeof(int) list[2]+ 2·sizeof(int) list[3]+ 3·sizeof(int) list[4]+ 4·sizeof(int) list[i] in C programs, C interprets it as a pointer to an integer whose address is the one in the table above int *list1; pointer variable to an int int list2[5]; five memory locations for holding integers are reserved Networking Laboratory 54/78

Algorithms Representation of Multidimensional Arrays Internal Representation of Multidimensional Arrays  How to state n-dimensional array into 1-dimensional array?  How to retrieve arbitrary element in a[upper0][upper1]···[uppern-1] the number of elements in the array n-1 upper i i=0 e.g.) a[10][10][10] → 10*10*10 = 1000 (units) Networking Laboratory 55/78

Algorithms 1-dimensional Array Starting-address + offset-value  Assume  : starting-address 1-dimensional array a[u 0 ] a[0] :  a[1] :  + 1 : : a[u 0 -1] :  + (u 0 - 1) & a[i] = α + i Networking Laboratory 56/78

Algorithms 2-dimensional Array 2-dimensional array a[u 0 ][u 1 ] a[i][j] = α + i·u 1 + j ?i j Networking Laboratory 57/78

Algorithms Stacks and Queues Networking Laboratory 58/78

Algorithms Stack Abstract Data Type ADT stack Last-In-First-Out (LIFO)  Ordered list, insertions and deletions are made at one end called the “top”  Given stack S = (a 0, ···, a n-1 ) a 0 : bottom element a n-1 : top element a i : on top of element a i-1 (0<i<n) Inserting and deleting elements in stack top A B A C B A D C B A E D C B A D C B A Networking Laboratory 59/78

Algorithms Implementing a Stack Using a one-dimensional array stack[MAX_STACK_SIZE] #define MAX_STACK_SIZE 100 typedef struct { int key; } element; element stack[MAX_STACK_SIZE]; int top = -1; Structure element consists of only a key field, and we can add fields to or modify to meet the requirements of the application Networking Laboratory 60/78

Algorithms Push and Pop Push void push(int *ptop, element item) { if (*ptop >= MAX_STACK_SIZE - 1) { stack_full(); return; } stack[++*ptop] = item; } Pop element pop(int *ptop) { if (*ptop == -1) return stack_empty(); return stack[(*ptop)--]; } push(&top, item) pop(&top, item) Networking Laboratory 61/78

Algorithms ADT queue First-In-First-Out (FIFO)  Ordered list  All insertions are made at one end called “rear”  All deletions are made at the other end called “front” Inserting and deleting elements in queue Queue Abstract Data Type rear A B A C B A D C B A D C B front front & rear A Networking Laboratory 62/78

Algorithms Implementing a Queue A one-dimensional array, and two variables: front and rear #define MAX_QUEUE_SIZE 100 typedef struct { int key; /* other fields */ } element; element queue[MAX_QUEUE_SIZE]; int rear = -1; int front = -1; Networking Laboratory 63/78

Algorithms Add and Delete Add to a queue void addq(int *prear, element item) { if (*prear == MAX_QUEUE_SIZE - 1) { queue_full(); return; } queue[++*prear] = item; } Delete from a queue element deleteq(int *pfront, int rear) { if (*pfront == rear) return queue_empty(); return queue[++*front]; } In deleteq() rear is used to check for an empty queue addq(&rear, item) deleteq(&front, rear) Networking Laboratory 64/78

Algorithms (1/3) Circular Queues (1/3) More efficient queue representation  Regarding the array queue[MAX_QUEUE_SIZE] as circular  Initially front and rear to 0 rather than -1  The front index always points one position counterclockwise from the first element in the queue  The rear index points to the current end of the queue Networking Laboratory 65/78

Algorithms (2/3) Circular Queues (2/3) Empty queue [1] [2][3] [4] [0][5] front = 0 rear = 0 [1] [2][3] [4] [0][5] front = 0 rear = 3 J3 J1 J2 Empty and nonempty circular queues Networking Laboratory 66/78

Algorithms (3/3) Circular Queues (3/3) Full queue [1] [2][3] [4] [0][5] front = 0 rear = 5 [1] [2][3] [4] [0][5] front = 4 rear = 3 J9 J7 J8 J1 J2J3 J4 J5J6J5 Full circular queues Networking Laboratory 67/78

Algorithms Implementing Insertions and Deletions Use modulus operator Circular rotation of the rear *rear = (*rear + 1) % MAX_QUEUE_SIZE Circular rotation of the front *front = (*front + 1) % MAX_QUEUE_SIZE; Networking Laboratory 68/78

Algorithms Add to a Circular Queue Add an item void addq(int front, int *rear, element item) { *rear = (*rear + 1) % MAX_QUEUE_SIZE; if (front == *rear) { queue_full(rear); /* reset rear and print error */ return; } queue[*rear] = item; } rotate rear before we place the item in queue[rear] addq(front, &rear, item) Networking Laboratory 69/78

Algorithms Delete from a Circular Queue Delete an item element deleteq(int *front, int rear) { element item; if (*front == rear) return queue_empty(); /* queue_empty returns an error key */ *front = (*front + 1) % MAX_QUEUE_SIZE; return queue[*front]; } deleteq(&front, rear) Networking Laboratory 70/78

Algorithms Lists Networking Laboratory 71/78

Algorithms Singly Linked Lists Compose of data part and link part  Link part contains address of the next element in a list  Non-sequential representations  Size of the list is not predefined  Dynamic storage allocation and deallocation batsatcatvat NULL ptr Networking Laboratory 72/78

Algorithms Insertion of Singly Linked Lists To insert the word mat between cat and sat 1) Get a currently unused node (paddr) 2) Set paddr’s data to mat 3) Set paddr’s link to point to the address found in the link of the node cat 4) Set the link of the node cat to point to paddr batsatcatvat NULL ptr mat Networking Laboratory 73/78

Algorithms Deletion of Singly Linked Lists To delete mat from the lists 1) Find the element that immediately precedes mat, which is cat 2) Set its link to point to mat’s link - No data movement in insert and delete operation batsatcatvat NULL ptr mat Networking Laboratory 74/78

Algorithms Doubly Linked Lists (1/2) Problems of singly linked lists  Move to only one way direction  Hard to find the previous node  Hard to delete the arbitrary node Doubly linked circular lists  Doubly lists + circular lists  Allow two links  Two way direction Networking Laboratory 75/78

Algorithms Doubly Linked Lists (2/2) Doubly linked circular lists with head node head node llinkitemrlink Networking Laboratory 76/78

Algorithms Insertion of Doubly Linked Lists Insertion into doubly linked circular lists void dinsert(node_ptr node,node_ptr newnode) { /* insert newnode to the right of node */ newnode->llink = node; newnode->rlink = node->rlink; node->rlink->llink = newnode; node->rlink = newnode; } time: O(1) dinsert(node, newnode) newnode node newnode node Networking Laboratory 77/78

Algorithms Deletion of Doubly Linked Lists Deletion from a doubly linked circular lists void ddelete(node_ptr node, node_ptr deleted) { /* delete from the doubly linked list */ if (node == deleted) printf(“Deletion of head node not permitted.\n”); else { deleted->llink->rlink = deleted->rlink; deleted->rlink->llink = deleted->llink; free(deleted); } time: O(1) node deleted node ddelete(node, deleted) deleted node Networking Laboratory 78/78