Copyright 2000-2010 Networking Laboratory C programming and Data Structures Overview T. H. Cormen,...

78
Copyright 2000-2010 Networking Laboratory C programming and C programming and Data Structures Overview 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 [email protected]

Transcript of Copyright 2000-2010 Networking Laboratory C programming and Data Structures Overview T. H. Cormen,...

Copyright 2000-2010 Networking Laboratory

C programming and C programming and Data Structures OverviewData Structures Overview

T. H. Cormen, C. E. Leiserson and R. L. RivestIntroduction to Algorithms, 2nd Edition, MIT Press, 2001

Sungkyunkwan University

Hyunseung [email protected]

Algorithms

ContentsContents

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 Function Definitions (1/2)(1/2)

Function 이 호출되기 전 반드시 해당 Function 을 다음 형식으로 정의해야 한다 .

Networking Laboratory 7/78

Algorithms

Function Definitions Function Definitions (2/2)(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 The ReturnReturn Statement Statement

Function 의 실행 종료 , 호출한 곳으로 control 을 이전하는 statement

생략 시는 function body 끝의 ‘ }’ 를 만났을 때 자동 return 복수개의 return 문 사용 가능

단 , 하나의 Function 에서 두 개의 값을 동시에 return 할 수 없음

Networking Laboratory 9/78

Algorithms

The Return ValueThe Return Value

Networking Laboratory 10/78

Algorithms

Function Prototypes Function Prototypes (1/2)(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 Function Prototypes (2/2)(2/2)

Argument 와 parameter 의 type 이 일치하지 않는 경우 function prototype 에서 지정된 type 으로 convert 됨 .

Networking Laboratory 12/78

Algorithms

Function Definition OrderFunction 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( )main( ) 안에서의 안에서의 Function DefinitionFunction Definition

Networking Laboratory 14/78

Algorithms

Developing Large Program Developing Large Program (1/2)(1/2)

대규모 Program 의 경우 , 여러 ~.h 파일과 ~.c 파일로 나누어 작성할 수 있다 .

Team 에 의한 작업분담이 용이해진다 .

프로그램이 변경될 때마다 변경된 ~.c 파일만을 compile함으로서 시간 절약 가능

Networking Laboratory 15/78

Algorithms

Developing Large Program Developing Large Program (2/2)(2/2)

Networking Laboratory 16/78

Algorithms

Call by Value and Call by ReferenceCall 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 ValueExample of Call by Value

Networking Laboratory 18/78

Algorithms

Example of Call by ReferenceExample of Call by Reference

Networking Laboratory 19/78

Algorithms

Recursions

Networking Laboratory 20/78

Algorithms

Recursive CallRecursive Call

어떤 함수가 자기 자신을 호출하는 것

Networking Laboratory 21/78

Algorithms

FactorialFactorial 을 구하는 예제을 구하는 예제

Networking Laboratory 22/78

Algorithms

ArrayArray 의 평균을 구하는 예제의 평균을 구하는 예제

Networking Laboratory 23/78

Algorithms

Drawing Patterns on the Screen Drawing Patterns on the Screen (1/2)(1/2)

제곱근을 구하는 예제

Networking Laboratory 24/78

Algorithms

Drawing Patterns on the Screen Drawing Patterns on the Screen (2/2)(2/2)

역순으로 문자를 출력하는 예제 입력 받은 문장의 문자들을 역순으로 출력한다 .

Networking Laboratory 25/78

Algorithms

Structures

Networking Laboratory 26/78

Algorithms

ArrayArray 와 와 structurestructure 의 차이점의 차이점

array Array 의 모든 element 는 같은 type 이여야 한다 . Index 를 사용하여 각 element 를 access 한다 .

structure 다른 type 의 element 로 구성 될 수 있다 있다 . 각 element 는 name 을 갖는다 . Name 에 의해 각 element 를 access 한다 .

Networking Laboratory 27/78

Algorithms

Struct DeclarationStruct Declaration

Collection of members(/elements)

Networking Laboratory 28/78

Algorithms

Structure TagStructure Tag

정의 되는 특정 structure 를 지정하기 위한 name

한 번 structure tag 인 part 가 정의되면 , 이제 tag 를 사용하여 같은 structure type 으로 선언할 수 있다 .

Networking Laboratory 29/78

Algorithms

Structure TagStructure Tag 와 변수 동시 선언와 변수 동시 선언

structure tag 를 이용하여 선언된 변수는 같은 structure type

Networking Laboratory 30/78

Algorithms

Compatible Structure Compatible Structure (1/2)(1/2)

같은 type 의 structure variable 이면 서로 assign 가능

compatible types 의 조건 Structure 정의와 동시에 선언되는 모든 variables 같은 type 의 structure 즉 같은 tag 에 의해 선언된 모든 variables

Networking Laboratory 31/78

Algorithms

Compatible Structure Compatible Structure (2/2)(2/2)

compatible type 이 아닐 경우 =, ==, != 불가능

Networking Laboratory 32/78

Algorithms

Memory AllocationMemory Allocation

Structure 로 선언된 데이터 type 은 각 member 들이 메모리 내에 순차적으로 할당된다 . part1 의 base address 가 200 이고 ,

integer size 가 4byte 라 가정하면 ,

오른쪽 그림과 같이 메모리가 할당됨

Networking Laboratory 33/78

Algorithms

Accessing a Member Accessing a Member (1/3)(1/3)

struct member operator ‘.’ Structure 의 각 member 를 access 하기 위해 ‘ .’ 를 사용한다 .

Networking Laboratory 34/78

Algorithms

Accessing a Member Accessing a Member (2/3)(2/3)

member operation

Networking Laboratory 35/78

Algorithms

Accessing a Member Accessing a Member (3/3)(3/3)

structure pointer

Networking Laboratory 36/78

Algorithms

Structures as ArgumentStructures as Argument

call-by-value 로 struct 가 copy 되어 사용 된다 .

Networking Laboratory 37/78

Algorithms

Struct PointerStruct Pointer 사용 사용 (1/2)(1/2)

call-by-reference 로 struct 의 address 를 전달한다 .

Networking Laboratory 38/78

Algorithms

Struct PointerStruct Pointer 사용 사용 (2/2)(2/2)

Networking Laboratory 39/78

Algorithms

The Use of typedef The Use of typedef (1/2)(1/2)

data type 의 name 을 재 정의 하기 위해 사용 readability 의 증가

Networking Laboratory 40/78

Algorithms

The Use of typedef The Use of typedef (2/2)(2/2)

typedef 를 사용 , struct type 을 새로운 type 으로 선언

Networking Laboratory 41/78

Algorithms

Pointers

Networking Laboratory 42/78

Algorithms

Pointer VariablePointer Variable

포인터 변수는 변수명은 같으나 변수선언을 할 때 * 연산자를 사용한다 . int *a; → int 형 포인터

포인터변수는 타입에 상관없이 4 바이트다 .

Networking Laboratory 43/78

Algorithms

Passing Pointers to Functions Passing Pointers to Functions (1/4)(1/4)

포인터를 argument 로 하는 함수 예제

Networking Laboratory 44/78

Algorithms

Passing Pointers to Functions Passing Pointers to Functions (2/4)(2/4)

포인터를 argument 로 하는 함수 예제

Networking Laboratory 45/78

Algorithms

Passing Pointers to Functions Passing Pointers to Functions (3/4)(3/4)

포인터를 argument 로 하는 함수 예제

Networking Laboratory 46/78

Algorithms

Passing Pointers to Functions Passing Pointers to Functions (4/4)(4/4)

포인터를 argument 로 하는 함수 사용시 유의점

Networking Laboratory 47/78

Algorithms

Exercise ProblemExercise Problem

pointer 의 주소 할당 문제

Networking Laboratory 48/78

Algorithms

ApproachesApproaches

pointer 의 예제

Networking Laboratory 49/78

Copyright 2000-2010 Networking Laboratory

Data Structures OverviewData Structures Overview

Sungkyunkwan University

Hyunseung [email protected]

Algorithms

ContentsContents 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 Arrays (1/2)(1/2)

An array is a set of pairs, <index, value>, 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 Arrays (2/2)(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 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

upperi

i=0

e.g.) a[10][10][10]

→ 10*10*10 = 1000 (units)

Networking Laboratory 55/78

Algorithms

1-dimensional Array1-dimensional Array

Starting-address + offset-value Assume : starting-address

1-dimensional array a[u0]

a[0] :

a[1] : + 1

: :

a[u0-1] : + (u0 - 1)

&a[i] = α + i

Networking Laboratory 56/78

Algorithms

2-dimensional Array2-dimensional Array

2-dimensional array a[u0][u1]

a[i][j] = α + i·u1 + j

0 1 · · · u1 - 10 +1 +(u1-1)1···

u0 - 1

?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 = (a0, ···, an-1)

a0 : bottom element

an-1 : top element

ai : on top of element ai-1 (0<i<n)

Inserting and deleting elements in stack

topAtopB

A

topCBA

topDCBA

topEDCBA

topDCBA

Networking Laboratory 59/78

Algorithms

Implementing a StackImplementing 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 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

rearA

rearB

A

rearC

B

A

rearD

C

B

A

rearD

C

B

front

frontfrontfrontfrontfront& rear

A

Networking Laboratory 62/78

Algorithms

Implementing a QueueImplementing a Queue

A one-dimensional array, and two variables: front and rear

#define MAX_QUEUE_SIZE 100typedef 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

Circular Queues (1/3)(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

Circular Queues (2/3)(2/3)

Empty queue

[1]

[2] [3]

[4]

[0] [5]

front = 0rear = 0

[1]

[2] [3]

[4]

[0] [5]

front = 0rear = 3

J3

J1

J2

Empty and nonempty circular queues

Networking Laboratory 66/78

Algorithms

Circular Queues (3/3)(3/3)

Full queue

[1]

[2] [3]

[4]

[0] [5]

front = 0rear = 5

[1]

[2] [3]

[4]

[0] [5]

front = 4rear = 3

J9

J7

J8

J1

J2 J3

J4

J5 J6 J5

Full circular queues

Networking Laboratory 67/78

Algorithms

Implementing Insertions and DeletionsImplementing 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 QueueAdd 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 QueueDelete 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

ListsLists

Networking Laboratory 71/78

Algorithms

Singly Linked Lists 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

bat satcat vat NULL

ptr

Networking Laboratory 72/78

Algorithms

Insertion of Singly Linked ListsInsertion 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

bat satcat vat NULL

ptr

mat

Networking Laboratory 73/78

Algorithms

Deletion of Singly Linked ListsDeletion 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

bat satcat vat NULL

ptr

mat

Networking Laboratory 74/78

Algorithms

Doubly Linked Lists Doubly Linked Lists (1/2)(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 Doubly Linked Lists (2/2)(2/2)

Doubly linked circular lists with head node

head node

llink item rlink

Networking Laboratory 76/78

Algorithms

Insertion of Doubly Linked ListsInsertion 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)1.

2.

3.

4.

dinsert(node, newnode)

newnode

node

341 2

node

newnode

1

23

4

newnode

node

Networking Laboratory 77/78

Algorithms

Deletion of Doubly Linked ListsDeletion 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