data structures - gabriel istrategabrielistrate.weebly.com/uploads/2/5/2/6/2526487/curs2.pdf ·...

32
Data Structures Instructor: Gabriel Istrate [email protected] Data Structures – p.1/32

Upload: lythuan

Post on 24-Apr-2018

235 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: Data Structures - Gabriel Istrategabrielistrate.weebly.com/uploads/2/5/2/6/2526487/curs2.pdf · File data type • File: generic term for external data structures. Ordered set/collection

Data Structures

Instructor: Gabriel Istrate

[email protected]

Data Structures – p.1/32

Page 2: Data Structures - Gabriel Istrategabrielistrate.weebly.com/uploads/2/5/2/6/2526487/curs2.pdf · File data type • File: generic term for external data structures. Ordered set/collection

Pointers and reference variables

int n =5, *p = &n, &r =n;.r is a reference variable. Must be initialized in definition as reference to a particularvariable.

reference: different name for/constant pointer to variable.cout << n << ’ ’<< *p<<’ ’<< r<< endl;

5 5 5

n= 7 (*p = 7, r = 7)

7 7 7

BEST WAY TO PASS PARAMETER: const reference variables;

Data Structures – p.2/32

Page 3: Data Structures - Gabriel Istrategabrielistrate.weebly.com/uploads/2/5/2/6/2526487/curs2.pdf · File data type • File: generic term for external data structures. Ordered set/collection

Generic Classes/Functions: Motivation

swap two integers

void swapint(int *a, int *b){

int temp = *a;

*a = *b;

*b = temp;

}

swap two reals

void swapfloat(float *a, float *b){

float temp = *a;

*a = *b;

*b = temp;

}

template<class genType,int size=50>

class genClass2{ . . .

genType storage[size];Data Structures – p.3/32

Page 4: Data Structures - Gabriel Istrategabrielistrate.weebly.com/uploads/2/5/2/6/2526487/curs2.pdf · File data type • File: generic term for external data structures. Ordered set/collection

Generic Classes/Functions

template<class genType>

(genType &el1, genType &el2){

genType tmp = el1;

el1 = el2;

el2 = tmp;

}

code reuse: more general.

Data Structures – p.4/32

Page 5: Data Structures - Gabriel Istrategabrielistrate.weebly.com/uploads/2/5/2/6/2526487/curs2.pdf · File data type • File: generic term for external data structures. Ordered set/collection

Generic Classes/Functions (II)

template<class genType>

class genClass{

genType storage[50];

...

}

template<class genType,int size=50>

class genClass2{

genType storage[size];

...

}

genClass <int> intObject1;

genClass2<int,100> intObject2;

Data Structures – p.5/32

Page 6: Data Structures - Gabriel Istrategabrielistrate.weebly.com/uploads/2/5/2/6/2526487/curs2.pdf · File data type • File: generic term for external data structures. Ordered set/collection

File data type

• File: generic term for external data structures. Ordered set/collection ofhomogeneous data.

• Example: data written to a printer: character sequences separated by newline.

• End-of-file: generated by the operating system. OS dependent.

• Sequential files have no additional inherent structure - any additional structuremust be imposed by the program reading and writing the file.

Data Structures – p.6/32

Page 7: Data Structures - Gabriel Istrategabrielistrate.weebly.com/uploads/2/5/2/6/2526487/curs2.pdf · File data type • File: generic term for external data structures. Ordered set/collection

File operations

• Creation.

• Reading.

• Update. Append/modify/erase.

• C: FILE * fp; FILE *fopen(const char *FileName, const char

*Mode);

Data Structures – p.7/32

Page 8: Data Structures - Gabriel Istrategabrielistrate.weebly.com/uploads/2/5/2/6/2526487/curs2.pdf · File data type • File: generic term for external data structures. Ordered set/collection

Files in C++

• the concept of streams (of dbytes).

• <iostream>: stream library, providing input/output facilities.

• standard input stream cin, standard output stream cout, standard error stream cerr.

• cin >> a; cout << a;

• Stream variables. Can be bound to files (physical memory). Different types(ifstream, ofstream, fstream) based on direction: read, write, rw.

Data Structures – p.8/32

Page 9: Data Structures - Gabriel Istrategabrielistrate.weebly.com/uploads/2/5/2/6/2526487/curs2.pdf · File data type • File: generic term for external data structures. Ordered set/collection

Sequences/files in C++

• ifstream InFile; // declares file handle called InFile

ofstream OutFile; // declares file handle called OutFile

fstream IOFile;

• binding stream to file: InFile.open("datafilein.txt", ios::in); //for

reading only

OutFile.open("datafileout.txt", ios::out); //for writing

IOFile.open("datafile",ios::in|ios::out); //for reading&

writing

Data Structures – p.9/32

Page 10: Data Structures - Gabriel Istrategabrielistrate.weebly.com/uploads/2/5/2/6/2526487/curs2.pdf · File data type • File: generic term for external data structures. Ordered set/collection

Sequences/files in C++(II)

• calls return FALSE if stream could not be opened.

• char filename="datafile.txt";

InFile.open(filename, ios::in);

if (!InFile) {

cout << "file "<< filename << " could not be opened."<< endl;

exit(1);

}

Data Structures – p.10/32

Page 11: Data Structures - Gabriel Istrategabrielistrate.weebly.com/uploads/2/5/2/6/2526487/curs2.pdf · File data type • File: generic term for external data structures. Ordered set/collection

Recursive data Structures

Data structures in which members are other data structures.

• C: struct family tree

{

char name[20];

struct family tree *father, *mother;

};

• C++ class family tree{

public:

family tree();

family tree(family tree &);

family tree();

char * getName();

family tree* getMotherFamilyTree();

family tree* getFatherFamilyTree();

private:

char name[20]

family tree *father, *mother;

} Data Structures – p.11/32

Page 12: Data Structures - Gabriel Istrategabrielistrate.weebly.com/uploads/2/5/2/6/2526487/curs2.pdf · File data type • File: generic term for external data structures. Ordered set/collection

Lists

• A list is a sequence of nodes all having the same type.

• a1, . . . , an, n the list length.

• nodes linearly ordered by their position in the list.

• more than one variant of a list based on operations want to implement fast.

Data Structures – p.12/32

Page 13: Data Structures - Gabriel Istrategabrielistrate.weebly.com/uploads/2/5/2/6/2526487/curs2.pdf · File data type • File: generic term for external data structures. Ordered set/collection

Possible operations on lists

• accessing the i’th element to examine or modify its fields.

• inserting a new node before the i’th one.

• deleting the i’th node.

• merging two or more lists into a single one;

• splitting a list into two or more lists;

• cloning a list;

• determining the list length;

• sorting the list nodes in a certain order based on certain node fields;

• searching a list for a node with a certain field value.

Data Structures – p.13/32

Page 14: Data Structures - Gabriel Istrategabrielistrate.weebly.com/uploads/2/5/2/6/2526487/curs2.pdf · File data type • File: generic term for external data structures. Ordered set/collection

Pause to ponder

• Why do we need lists ? Why aren’t vectors enough ?

• Answer: vectors and lists are made for different things. Performance of operations.

Data Structures – p.14/32

Page 15: Data Structures - Gabriel Istrategabrielistrate.weebly.com/uploads/2/5/2/6/2526487/curs2.pdf · File data type • File: generic term for external data structures. Ordered set/collection

Example: Josephus problem

• Flavius Josephus, a Jewish historian living in the 1st century.

• siege of Yodfat: he and his 40 comrade soldiers were trapped in a cave, the exitblocked by Romans.

• Chose suicide over capture and decided that they would form a circle and starteliminating people using a step of three.

• Compute last two people remaining.

Data Structures – p.15/32

Page 16: Data Structures - Gabriel Istrategabrielistrate.weebly.com/uploads/2/5/2/6/2526487/curs2.pdf · File data type • File: generic term for external data structures. Ordered set/collection

Can you implement with vectors ?

• SURE !

• But ... need to delete elements "in the middle"

• With vectors: move elements around. Performance an issue.

• Can reserve space for all numbers and use 0/1 to indicate that the given index hasarrived. Memory nonoptimal.

• This is what linked lists are good at: compact memory, fast insertion/deletion O(1)

time.

Data Structures – p.16/32

Page 17: Data Structures - Gabriel Istrategabrielistrate.weebly.com/uploads/2/5/2/6/2526487/curs2.pdf · File data type • File: generic term for external data structures. Ordered set/collection

Implementing linked lists with pointers

• node: holds a pointer to next node, in addition to extra information.

• List access: pointer to the first node.

• Useful: also pointer to last node.

Data Structures – p.17/32

Page 18: Data Structures - Gabriel Istrategabrielistrate.weebly.com/uploads/2/5/2/6/2526487/curs2.pdf · File data type • File: generic term for external data structures. Ordered set/collection

Linked lists: nodes

struct node {

int key;

char info[10];

struct node *next;

};

typedef struct node Tnode;

struct list{

Tnode* first;

Tnode* last;

}

typedef struct list LIST;

LIST l;

Data Structures – p.18/32

Page 19: Data Structures - Gabriel Istrategabrielistrate.weebly.com/uploads/2/5/2/6/2526487/curs2.pdf · File data type • File: generic term for external data structures. Ordered set/collection

Linked lists: nodes

class node {

public:

node();

node(int, node *);

node(const node &);

∼node();

int getInfo();

node * getNextNode();

node * setNextNode(node *);

private:

int info;

node *next;

};

Data Structures – p.19/32

Page 20: Data Structures - Gabriel Istrategabrielistrate.weebly.com/uploads/2/5/2/6/2526487/curs2.pdf · File data type • File: generic term for external data structures. Ordered set/collection

Linked lists

class list{

public:

list(); ∼list(); . . .

node *getFirstNode();

node *getLastNode();

void addToHead(int);

void addToTail(int);

bool isEmpty();

private:

node* head;

node* tail;

}

Data Structures – p.20/32

Page 21: Data Structures - Gabriel Istrategabrielistrate.weebly.com/uploads/2/5/2/6/2526487/curs2.pdf · File data type • File: generic term for external data structures. Ordered set/collection

Implementing constructors

node::node(int i, node *n){

// create new node

info = i;

next = n;

}

list::list(){

// create new (empty) list

head=tail=0;

}

• Reminder: default values for parameters (node constructor).

• Allows calling constructor with one argument: node(10) vs node(10,0);

Data Structures – p.21/32

Page 22: Data Structures - Gabriel Istrategabrielistrate.weebly.com/uploads/2/5/2/6/2526487/curs2.pdf · File data type • File: generic term for external data structures. Ordered set/collection

Constant reference parameters

node::node(const node & n){

// create a copy of node n

info = n.getInfo();

next = n.getNextNode();

}

• ... compiler complains (this pointer).

• Want: Constructor does not modify source node n;

• Solution: constant functions.

Data Structures – p.22/32

Page 23: Data Structures - Gabriel Istrategabrielistrate.weebly.com/uploads/2/5/2/6/2526487/curs2.pdf · File data type • File: generic term for external data structures. Ordered set/collection

Testing node class

#include <iostream>

using namespace std;

#include‘‘node.h’’

int main(int argc,char **argv){

// simple program to test our node class

node n(10,0);

cout << "node info is: "<< n.getInfo()<< endl;

n.setInfo(20);

cout << "now node info is: "<<n.getInfo()<< endl;

node n2(30,0);

n.setNextNode(&n2);

cout <<"next node info is: "<<n.getNextNode()->getInfo()<< endl;

node n3(n2);

cout << ‘‘info in node n3 is: ’’<<n3.getInfo()<< endl;

return 0;

} Data Structures – p.23/32

Page 24: Data Structures - Gabriel Istrategabrielistrate.weebly.com/uploads/2/5/2/6/2526487/curs2.pdf · File data type • File: generic term for external data structures. Ordered set/collection

Testing node class (II)

• Test your code as early as possible !

• We’ll hear about: unit testing.

• For now: main program. argv, argc.

• Can also write char *argc[0].

• argc[0] represents program name, argc[1] to argc[argv-1] parameter list.

• e.g. “test 2 3”. argc[1]=“2”, argc[2]=“3” (strings).

• C++ syntax for function call: b.bar().

• If a is a pointer to b, syntax is a− > bar().

Data Structures – p.24/32

Page 25: Data Structures - Gabriel Istrategabrielistrate.weebly.com/uploads/2/5/2/6/2526487/curs2.pdf · File data type • File: generic term for external data structures. Ordered set/collection

Inserting nodes in the front of the list

• List is empty: set both head and tail pointers to n.

• Otherwise:

• set pointer next of n to the beginning of the list.

• set head pointer to n.

• When dereferencing a pointer remember it can be NULL !

• typical scenario: (a− > foo())− > bar(), where (a− > foo()) is a pointer to anobject (e.g. NODE).

Data Structures – p.25/32

Page 26: Data Structures - Gabriel Istrategabrielistrate.weebly.com/uploads/2/5/2/6/2526487/curs2.pdf · File data type • File: generic term for external data structures. Ordered set/collection

Inserting nodes in the front of the list

void List::addToHead(int info){

// create new node

head= new node(info,head);

// what about the tail pointer ?

/* if the list is empty it has to be set

to n as well */

if (tail == 0)

tail = head;

}

Data Structures – p.26/32

Page 27: Data Structures - Gabriel Istrategabrielistrate.weebly.com/uploads/2/5/2/6/2526487/curs2.pdf · File data type • File: generic term for external data structures. Ordered set/collection

Inserting nodes to the back of the list

void List::addToTail(int info){

if (tail != 0){

tail->setNextNode(new node(info));

tail = tail->getNextNode();

}else

head = tail = new node(info);

}

Data Structures – p.27/32

Page 28: Data Structures - Gabriel Istrategabrielistrate.weebly.com/uploads/2/5/2/6/2526487/curs2.pdf · File data type • File: generic term for external data structures. Ordered set/collection

Iterating through a linked list

• Initialize a pointer to the first element of the list.

• While the pointer is nonempty list the values pointed by it.

• Advance the pointer to the right.

• p = p− > getNextNode();

• Add the following procedure as a method to the List class.

Data Structures – p.28/32

Page 29: Data Structures - Gabriel Istrategabrielistrate.weebly.com/uploads/2/5/2/6/2526487/curs2.pdf · File data type • File: generic term for external data structures. Ordered set/collection

Iterating through a linked list

void List::PrintList(){

node *n = head;

if (n == 0){

cout << "list is empty" << endl;

}else

while (n != 0){

cout << n->getInfo() << " ";

n = n->getNextNode();

}

cout << endl;

}

Data Structures – p.29/32

Page 30: Data Structures - Gabriel Istrategabrielistrate.weebly.com/uploads/2/5/2/6/2526487/curs2.pdf · File data type • File: generic term for external data structures. Ordered set/collection

Variant: searching for information in a linked

list

• Iterate through list comparing the information with a target information.

• Return a pointer to the first node holding the right information.

• Possible: no node holds the right information. In this case return a null pointer

• RULE: check whether pointers are null or not ! Source of many problems.

Data Structures – p.30/32

Page 31: Data Structures - Gabriel Istrategabrielistrate.weebly.com/uploads/2/5/2/6/2526487/curs2.pdf · File data type • File: generic term for external data structures. Ordered set/collection

Searching for information in a linked list

node *List::FindInfo(int info){

node *n = head;

if (n == 0)

{

cout << "list is empty" << endl;

}else

while (n != 0)

if (n->getInfo() == info)

{

return n;

}else

{

n=n->getNextNode();

};

return 0;

}Data Structures – p.31/32

Page 32: Data Structures - Gabriel Istrategabrielistrate.weebly.com/uploads/2/5/2/6/2526487/curs2.pdf · File data type • File: generic term for external data structures. Ordered set/collection

Conclusions

• Wrapped up review of C/basic C++.• Reviewed sorting algorithms.• Files, fileIO in C++.• Started linked lists.

Any questions ?

Data Structures – p.32/32