data structures - gabriel istrategabrielistrate.weebly.com/uploads/2/5/2/6/2526487/curs2.pdf ·...
TRANSCRIPT
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
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
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
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
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
File operations
• Creation.
• Reading.
• Update. Append/modify/erase.
• C: FILE * fp; FILE *fopen(const char *FileName, const char
*Mode);
Data Structures – p.7/32
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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