Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Data Structures for Media Linked Lists. 2 Review: Abstract Data Types Review: Abstract Data Types Review: Pointers and References Review: Pointers and.

Similar presentations


Presentation on theme: "1 Data Structures for Media Linked Lists. 2 Review: Abstract Data Types Review: Abstract Data Types Review: Pointers and References Review: Pointers and."— Presentation transcript:

1 1 Data Structures for Media Linked Lists

2 2 Review: Abstract Data Types Review: Abstract Data Types Review: Pointers and References Review: Pointers and References Singly Linked List Singly Linked List Circular Lists Circular Lists Doubly Linked Lists Doubly Linked Lists Applications Applications Outline

3 3 We want to know whether two cups can hold the same amount of water We want to know whether two cups can hold the same amount of water What to do? What to do? Calculate the volume by mathematical formulas Calculate the volume by mathematical formulas Fill cup 1 by water, pour the water to cup 2, overflow? vice versa Fill cup 1 by water, pour the water to cup 2, overflow? vice versa … We only care about the result, not how to get the result We only care about the result, not how to get the result Abstract Data Type for cups! Abstract Data Type for cups! Abstract Data Type

4 4 Abstract Data Types Some advanced data types are very useful. People tend to create modules that group together the data types and the functions for handling these data types. (~ Modular Design) They form very useful toolkits for programmers. /*matrix.h*/ public __gc class Matrix { void PrintMatrix(..); Matrix AddMatrix(.); … }; When one search for a “ tool ”, he looks at how / what* the tools can do. i.e. He looks at the abstract data types (ADT). menu He needs not know how / what* the tools have been implemented.

5 5 e. g. The set ADT: Value: A set of elements Condition: elements are distinct. Operations for Set *s: 1. void Add(ELEMENT e) postcondition: e will be added to *s 2. void Remove(ELEMENT e) precondition: e exists in *s postcondition: e will be removed from *s 3. int Size() postcondition: the no. of elements in *s will be returned. … An ADT is a package of the declarations of a data type and the operations that are meaningful to it. We encapsulate the data type and the operations and hide them from the user. ADTs are implementation independent. Abstract Data Type

6 6 Value: A set of elements Condition: elements are distinct. The set ADT: 1. Definition of values involves definition definition condition (optional) condition (optional) Consists of 2 parts: Operations for Set *s: 1. void Add(ELEMENT e) postcondition: e will be added to * s 2. void Remove(ELEMENT e) precondition: e exists in * s postcondition: e will be removed from * s 3. int Size( ) postcondition: the no. of elements in * s will be returned. … 2. Definition of operations each operation involves header header precondition (optional) precondition (optional) postcondition postcondition Abstract Data Type

7 7 Phase Description Result Data Abstraction Data abstraction is an important method in program design Using the right data types => more efficient program Algorithms can be designed in terms of the abstract data type. We can defer decisions of data types until their uses are fully understood. 3. Implement the algorithm Construct a mathematical model + its operations ( ADT ) e.g., the model is a set, the problem is to list all elements. This phase is to express the algorithm in pseudocode, while figuring out the picture of the ADT. Implementation-independent: Not to think whether to use array or linked list etc.. Not to design how to implement the operations. A rough algorithm The ADT Data types and operations Implement the actual data types and the operations for the ADT 1. Problem Formulation 2. Design the algorithm (Suppose no ADT available yet.)

8 8 Value Type: variable contains data of that type Value Type: variable contains data of that type int A; double B; … int A; double B; … Reference Type: variable contains the address Reference Type: variable contains the address String * c; Object * d; … String * c; Object * d; … Pointers Pointers int y=5; int *ypointer; ypointer=&y;*ypointer=? Pointers and References c=1196 data 1196 ypointer y=5 60000 dereferencing References References int count = 1; int &cRef = count; ++cRef; What is the value of count?

9 9 String *text = “ hello ” ; If ( text->EndsWith( “ llo ” ) ) Console::WriteLine( “ {0} ends with llo ”, text); If ( (*text).EndWith( “ llo ” ) ) Console::WriteLine( “ {0} ends with llo ”, text); Remember: -> for pointer;. for dereference Remember: -> for pointer;. for dereference Call methods using pointers

10 10 Pass by Value int SquareByV(int a) { Return a * a; } int _tmain() { int x =2; SquareByV(x);} Passing Auguments Pass by Reference void SquareByP(int *cptr) { *cptr *= *cptr; } int _tmain() { int y =2; SquareByP(&y);} Pass by Reference void SquareByR(int &cRef) { cRef *=cRef; } int _tmain() { int z =2; SquareByR(z);} int * p : (int *) p *p: dereference (the data pointed by p) *: multiplication &a: the address of a A[]: array variable is a pointer

11 11 Question: When to use Call-by-value? When to use Call-by-reference? For security of data, we apply Call-by-reference only if necessary, e.g. (1) we really want the called function to change the data (2) the data is too big, i.e. Instead of copying a bulky data, e.g. a 100 byte record, (Call-by-value) we prefer to copy the memory address only (Call-by-reference) Passing Auguments

12 12 A Linear List (or a list, for short) is a sequence of n nodes x 1, x 2,.., x n whose essential structural properties involve only the relative positions between items as they appear in a line. A list can be implemented as A list can be sorted or unsorted. Arrays: statically allocated or dynamically allocated Linked Lists: dynamically allocated List

13 13 Each item in the list is a node Each item in the list is a node Linear Structure Linear Structure Node can be stored in memory consecutively /or not (logical order and physical order may be different) Node can be stored in memory consecutively /or not (logical order and physical order may be different) Singly Linked List datanext a0a0 a1a1 a2a2 first a0a0 a1a1 a2a2 a3a3 a4a4 

14 14 // ListNode.h #pragma once #include “ stdlib.h ” #using #using using namespace System; namespace LinkedListLibrary { public __gc class ListNode {public: ListNode( int ); ListNode( int, ListNode *); __property ListNode *get_Next() { return next; }…private: int data; ListNode *next; };} Singly Linked List // List.h #pragma once #include “ ListNode.h ” namespace LinkedListLibrary { public __gc class List {public: List( String * ); List(); //various member functions private: ListNode *first; String *name; }}

15 15 Operations: Operations: InsertNode: insert a new node into a list InsertNode: insert a new node into a list RemoveNode: remove a node from a list RemoveNode: remove a node from a list SearchNode: search a node in a list SearchNode: search a node in a list CountNodes: compute the length of a list CountNodes: compute the length of a list PrintContent: print the content of a list PrintContent: print the content of a list … Singly Linked List

16 16 Count a linked list: Use a pointer p to traverse the list first …… p //List.cpp int List::Count() { int result=0; ListNode *p=first; while (p!=NULL) {result++; p= p->getNext(); }}

17 17 Print a linked list: //List.cppList::Print(){ ListNode *p=first; while (p!=NULL) { Console::Write(S ” {0} ”, p->getData().ToString()); p=p->getNext();}} Use a pointer p to traverse the list first …… p

18 18 Search for a node: //List.cpp ListNode* List::Search(int data) { ListNode *p=first; while (p!=NULL) { if (p->getData()==data) return p; p=p->getNext();} return NULL; } Use a pointer p to traverse the list If found: return the pointer to the node, otherwise: return NULL. first …… p

19 19 Data comes one by one and we want to keep them sorted, how? Data comes one by one and we want to keep them sorted, how? Do search to locate the position Do search to locate the position Insert the new node Insert the new node Why is this correct? Why is this correct? Invariant Invariant We will encounter three cases of insert position We will encounter three cases of insert position Insert before the first node Insert before the first node Insert in the middle Insert in the middle Insert at the end of the list Insert at the end of the list One important case missing: Empty List One important case missing: Empty List Insert a node: Void List::InsertNode(ListNode* newnode) { if (first==NULL) first=newnode; else if (newnode->getData() getData() ) …}

20 20 Case 1: Insert before the first node Case 1: Insert before the first node newnode->next=first newnode->next=first first=newnode first=newnode Insert a node: newnode first …… newnode …… before insertafter insert first

21 21 Void List::InsertNode(ListNode* newnode) { if (first==NULL) first=newnode; else if (newnode->data data) {newnode->next=first;first=newnode;}else…} Insert a node: Case 1 In the following slides, we assume all the class member variables are public, so that the writings will be more clear Remember that in real coding, you should use functions getData(), setData(), getNext(), setNext() to access private class variables

22 22 Case 2: Insert in the middle Case 2: Insert in the middle newnode->next=p->next newnode->next=p->next p->next=newnode p->next=newnode Insert a node: newnode …… p newnode …… p before insertafter insert

23 23 Case 3: Insert at the end of the list Case 3: Insert at the end of the list newnode->next=p->next newnode->next=p->next p->next=newnode p->next=newnode Insert a node: newnode …… p newnode …… p before insertafter insert  

24 24 Void List::InsertNode(ListNode* newnode) { if (first==NULL) first=newnode; else if (newnode->data data) {newnode->next=first;first=newnode;}else{ ListNode* p=first; while(p->next!=NULL && newnode->data>p- >next->data) p=p->next; //p will stop at the last node or at the node //after which we should insert the new node //note that p->next might be NULL here newnode->next=p->next;p->next=newnode;}} Insert a node: Complete Solution

25 25 Some data become useless and we want to remove them, how? Some data become useless and we want to remove them, how? Search the useless node by data value Search the useless node by data value Remove this node Remove this node We will encounter two cases We will encounter two cases Removing a node at the beginning of the list Removing a node at the beginning of the list Removing a node not at the beginning of the list Removing a node not at the beginning of the list Remove a node:

26 26 Case 1: Remove a node at the beginning of the list Case 1: Remove a node at the beginning of the list Current status: the node pointed by “ first ” is unwanted Current status: the node pointed by “ first ” is unwanted The action we need: q=first; first=q->next The action we need: q=first; first=q->next Remove a node: before remove after remove first …… q q first

27 27 Case 2: Remove a node not at the beginning of the list Case 2: Remove a node not at the beginning of the list Current status: q == p->next and the node pointed by q is unwanted The action we need: p->next=q->next Remove a node: before remove after remove …… p q p q

28 28 Void List::RemoveNode(ListNode* q) { //remove at the beginning of a list if (q==first) first=first->next;else //remove not at the beginning { ListNode* p=first; while(p->next!=q)p=p->next;p->next=q->next;}} Remove a node: Complete Solution Remember: 1.In real coding, you should also consider exceptions 2.Design of Linked List ADT is up to you, you can choose suitable functions to be member functions, e.g. InsertAtFront(), RemoveAtFront(). For each function, you can have your own way to implement it

29 29 So many cases with Insert and Remove operations So many cases with Insert and Remove operations We want simpler implementations! We want simpler implementations! One way to simplify: One way to simplify: keep an extra node at the front of the list keep an extra node at the front of the list Dummy Header Node …… Dummy Header node first Data nodes The value of these nodes are our data We don’t care about the value of this node.

30 30 One case remaining for insert One case remaining for insert Dummy Header Node newnode …… p newnode …… p before insert after insert

31 31 Void List::InsertNode(ListNode* newnode) { if (first==NULL) first=newnode; else if (newnode->data data) {newnode->next=first;first=newnode;}else{ ListNode* p=first; while(p->next!=NULL && newnode->data>p->next->data) p=p->next; //p will stop at the last node or at the node //after which we should insert the new node //note that p->next might be NULL here newnode->next=p->next;p->next=newnode;}} Insert a node: With Dummy Header

32 32 One case remaining for remove One case remaining for remove before remove after remove …… p q p q Dummy Header Node

33 33 Void List::RemoveNode(ListNode* q) { //remove at the beginning of a list if (q==first) first=first->next;else //remove not at the beginning { ListNode* p=first; while(p->next!=q)p=p->next;p->next=q->next;}} Remove a node: With Dummy Header

34 34 Suppose we are at the node a 4 and want to reach a 1, how? Suppose we are at the node a 4 and want to reach a 1, how? If one extra link is allowed: If one extra link is allowed: Circular Lists a0a0 a1a1 a2a2 a3a3 a4a4  first a0a0 a1a1 a2a2 a3a3 a4a4

35 35 Dummy header node can also be added to make the implementation easier Dummy header node can also be added to make the implementation easier Circular Lists a0a0 a1a1 a2a2 a3a3 first Dummy Header node We don’t care about the value of this node. first

36 36 Problem with singly linked list Problem with singly linked list When at a 4, we want to get a 3 When at a 4, we want to get a 3 When deleting node a 3, we need to know the address of node a 2 When deleting node a 3, we need to know the address of node a 2 When at a 4, it is difficult to insert between a 3 and a 4 When at a 4, it is difficult to insert between a 3 and a 4 If allowed to use more memory spaces, what to do? If allowed to use more memory spaces, what to do? Doubly Linked List a0a0 a1a1 a2a2 a3a3 a4a4  first LnextRnextData

37 37 To insert a node after an existing node pointed by p To insert a node after an existing node pointed by p Doubly Linked List p p DoublyLinkedList::InsertNode(ListNode *p, ListNode *newnode) { newnode->Lnext=p; newnode->Rnext=p->Rnext; if(p->Rnext!=NULL) p->Rnext->Lnext=newnode; p->Rnext=newnode; } newnode

38 38 To delete a node, we only need to know a pointer pointing to the node To delete a node, we only need to know a pointer pointing to the node Doubly Linked List p p DoublyLinkedList::RemoveNode(ListNode *p) { if(p->Lnext!=NULL) p->Lnext->Rnext=p->Rnext; if(p->Rnext!=NULL) p->Rnext->Lnext=p->Lnext; }

39 39 Doubly Linked List with Dummy Header Doubly Linked List with Dummy Header When empty When empty Doubly Circular Linked List? Doubly Circular Linked List? Further Extensions Dummy Header node Lnext Dummy Header Rnext

40 40 Linked allocation: Stores data as individual units and link them by pointers. Advantages of linked allocation: Efficient use of memory Facilitates data sharing No need to pre-allocate a maximum size of required memory No vacant space left Easy manipulation To delete or insert an item To join 2 lists together To break one list into two lists Variations Variable number of variable-size lists Multi-dimensional lists (array of linked lists, linked list of linked lists, etc.) Simple sequential operations (e.g. searching, updating) are fast Disadvantages: Take up additional memory space for the links Accessing random parts of the list is slow. (need to walk sequentially) Advantages / Disadvantages of Linked List

41 41 Applications Representing Convex Polygons A polygon is convex if it contains all the line segments connecting any pair of its points. Polygon: A closed plane figure with n sides. first

42 42 Review: Abstract Data Types Review: Abstract Data Types Review: Pointers and References Review: Pointers and References Singly Linked List Singly Linked List Circular Lists Circular Lists Doubly Linked Lists Doubly Linked Lists Dummy Header Dummy Header Applications: Representing Polygons Applications: Representing Polygons Summary


Download ppt "1 Data Structures for Media Linked Lists. 2 Review: Abstract Data Types Review: Abstract Data Types Review: Pointers and References Review: Pointers and."

Similar presentations


Ads by Google