5/09/2014 6:33 pm Monday Week 07 Page 1 of 9 http://www.cse.unsw.edu.au/~cs1921/14s2/slides/week07a/notes.html
Monday Week 07 Data and Memory
1/25
For today's lecture ... work through a series of programs dealing with linked lists, stacks and queues to ensure that you understand properly dynamic objects with links memory management via malloc() and free() separating definitions of data structures and operations from their implementation
Dynamic Data Structures
2/25
Dynamic data structures are built at runtime. Linked lists are an example. They are defined as: typedef struct node { DataT data; // e.g. int data; struct node *next } NodeT;
... Dynamic Data Structures
3/25
Iterating over an existing linked list NodeT *list NodeT *p = list; while (p != NULL) { ... p->data ... // do something with the data p = p->next; // move forward }
... Dynamic Data Structures
4/25
Creating a new list through iteration the wrong way NodeT *list;
5/09/2014 6:33 pm Monday Week 07 Page 2 of 9 http://www.cse.unsw.edu.au/~cs1921/14s2/slides/week07a/notes.html
int i; for (i = 1; i < N; i += 2) { list = makeNode(i); // create new node list = list->next; // move forward } printList(list);
... Dynamic Data Structures
5/25
Creating a new list through iteration the right way NodeT *list, *head; head = list = makeNode(1); // both point to the first node int i; for (i = 3; i < N; i += 2) { list->next = makeNode(i); // create and link new node list = list->next; // move forward } printList(head);
... Dynamic Data Structures
6/25
Stacks are a form of linked lists used to model: moving boxes placing and removing many rings on a (single) finger putting plates away in the cupboard and then setting the table many cars going down a one-way street that is blocked and having to back out again calling functions in C page-visited history in a Web browser undo sequence in a text editor checking for balanced braces postfix calculator They are examples of Last In, First Out (LIFO)
... Dynamic Data Structures
7/25
Queues are a form of linked lists used to model: the checkout at a supermarket people standing at a ticket window people queueing to go onto a bus cars queueing to go onto a ferry
- bjects flowing through a pipe (where they cannot overtake each other)