advance data structure review of chapter 4 張啟中. overview of chapter 4 type of list 4.1 singly...
Post on 21-Dec-2015
217 Views
Preview:
TRANSCRIPT
Advance Data StructureReview of Chapter 4
張啟中
Overview of Chapter 4
Type of List 4.1 Singly Linked Lists
4.2 Representing Lists in C++ 4.3 Reusable Linked List Class
4.4 Circular Lists 4.9 Doubly Linked Lists 4.10 Generalized Lists 4.12 Heterogeneous Lists
Example 4.5 Linked Stacks and Queues 4.6 Polynomials 4.7 Equivalence Classes 4.8 Sparse Matrices
Array-Based Ordered List
優點 可隨意存取任何節點 O(1)
缺點 儲存空間固定,而且必須事先指定。 插入與刪除需較多的時間 O(n)
Array-Based Ordered List: Insert
k
0 1 2 k-1 MaxSize -1
12 3 19 ?1810 ?
k+1
0 1 2 k MaxSizre -1
12 3 18105 ?
k+1
0 1 2 k MaxSize -1
12 3 44 18105 ?
Insert (2, 44)
Array-Based Ordered List: Delete
k
0 1 2 k-1 MaxSize -1
12 3 19 ?1810 ?
Delete
k
0 1 2 k-1 MaxSize -1
12 3 ?1810 ?
k-1
0 1 2 k-1 MaxSize -1
12 3 ??18 ?
k-2
34
Delete(2)
Linked List HAT
CAT
EAT
WAT
BAT
FAT
VAT
…
1
2
3
4
5
6
7
8
9
10
11
15
4
9
0
3
1
7
…
data link
Linked List 的優缺點
資料不一定要以連續的記憶體儲存,可以任意的放置。 儲存空間不受限制,且不需事先指定
資料新增與刪除,不需搬移其餘資料 新增與刪除操作時間為 O(1)
由於資料可能放置在記體位置,所以存取資料必須一個一個的循序操作,無法隨意存取。 存取資料需 O(n)
Singly Linked Lists
BAT CAT EAT WAT 0first
BAT CAT EAT WATfirst
Circular Lists
Doubly Linked Lists
BAT CAT EAT
-
dataLeftLink RightLink
A 0 0F T T
P
BF C 0F
Generalized Lists
Head Node
Heterogeneous Lists
BAT 123 50.2 0first John
170
58
Singly Linked Lists: Insert
BAT CAT EAT HAT 0first
GAT 0x
FAT
(1)
(2)(3)
Singly Linked Lists: Delete
BAT CAT EAT HAT 0first FAT
(2)
x(1)
(3)
Implementing Node of Linked Lists The Node of Linked list include:
Data field: 儲存資料 Link field: 指向下一個 node
根據需求,定義出 List Node 的 class Example:class ThreeLetterNode { private: char data[3]; ThreeLetterNode *link;};
Implementing Linked Lists 依據 List Node 的定義,設計 Lists ,可能有以下三
種的設計方法: Design Attempt 1
Use a global variable which is a pointer of ListNode Example: ThreeLetterNode *first; Unable to access to private data members: data and link.
Design Attempt 2 Make public member functions in class ListNode. Defeat the purpose of data encapsulation.
Design Attempt 3 Composition Class (HAS-A)
Friend Classes. Nested Classes. Inheritance with private
Design Attempt 3: Composition Classes Composition by Friend Classed//forward delcarionclass ThreeLetterList;class ThreeLetterNode{ friend class ThreeLetterList; private: char data[3];
ThreeLetterNode * link;};
class ThreeLetterList { public: //List Manipulation operations
. private: ThreeLetterNode *first;};
Composition by Nested Classedclass ThreeLetterList
{
public:
//List Manipulation operations
.
.
private:
//nested classclass ThreeLetterNode
{
public:
char data[3];
ThreeLetterNode *link;
};
ThreeLetterNode *first;
};
Design Attempt 3: Composition Classes
BAT CAT EAT WAT 0first
ThreeLetterList
ThreeLetterNode
List Manipulation operations == interface
BAT CAT EAT WAT 0first
ThreeLetterNode
實體圖
概念圖
Design Attempt 3: Composition Classes
Linked Lists 的所有節點資料完全隱藏,外界無法直接操作或存取節點資料,達成封裝( Encapsulation )的目的。
Linked Lists 的成員函式( member functions )可以自由存取 Linked Lists Node 的資料。
外界程式必須透過 Liked List 的成員函式來操作並存取節點資料。
Linked Lists Node 必須依實際需求重新設計,連帶 Linked Lists 的操作也需要修正!不夠完美,如何改進?
Design Attempt 3: Composition Classes 改進方式
Linked Lists Node 要能夠應付不同的資料型態,如何辦到? 用 C++ 的 template 機制!
Linked Lists 的成員函式必須要能夠操作不同資料型態的 Linked List Node 設計一個新的 iterators class ,負責去指向要操作
的資料節點, Linked List 成員函式則利用 iterators 來存取節點資料。
Design Linked Lists with Templatetemplate <class Type> class List ; //forward declaration template <class Type> class ListNode { friend class List<Type>;private: Type data; ListNode *link; };
template <class Type> class List { public: List() { first = 0;} //constructor initializing first to 0 // List manipulation operations …… private: ListNode<Type> *first; };
Container and Iterators
Containers ( 容器 ) A container class is a class that represents a data
structure that stores a number of data objects. (see book p121)
Iterators ( 迭代器 ) An iterator is an object that is used to traverse all t
he elements of a container class.
Linked Lists Iterators
template <class Type> class ListIterator { public: ListIterator(const List<Type> &l):list(l),current(l.first){}; bool NotNull(); bool NextNotNull(); Type* First(); Type* Next(); private: const List<Type>& list; // refers to an existing list ListNode<Type>* current; // points to a node in list } ;
Member function: see book p180. Program 4.9
Linked Lists Iterators Member Functiontemplate <class Type> //check that the current element in list is non-null Boolean ListIterator <Type>::NotNull() { if (current) return TRUE ; else return FALSE ; } template <class Type> //check that the next element in list is non-null Boolean ListIterator <Type>::NextNotNull() { if (current && current->link) return TRUE ; else return FALSE ; }
Linked Lists Iterators Member Functiontemplate <class Type> //return a pointer to the first element of list Type* ListIterator <Type>::First() { if (list.first) return &list.first->data ; else return 0 ; }
template <class Type> //return a pointer to the next element of list Type* ListIterator <Type>::Next() { if (current) { current = current->link ; if (current) return ¤t->data ; } else return 0 ; }
Design Linked Lists with Templatetemplate <class Type> class List ; //forward declaration template <class Type> class ListNode { friend class List<Type>;friend class ListIterator <Type>; private: Type data; ListNode *link; };
template <class Type> class List { friend class ListIterator <Type>;public: List() { first = 0;} //constructor initializing first to 0 //List manipulation operations …… private: ListNode<Type> *first; };
List Node
Lists
Reusing the Linked Lists Class 在大部分的應用中,我們會採取前面所設計的
一般化的 Linked Lists Class 來解決問題。 但有些情況,我們則必須直接設計新的 Linke
d Lists class ,例如: 考量執行效率。
stacks 與 queues 的實作 問題較複雜且有特別的需求時。
找出 equivalence class 。
Circular Lists
BAT CAT EAT WATfirst
BAT CAT EAT WAT last
Check Last Node: current->link == first;
Use the last node instead of the first node
Circular Lists with dummy head node
BAT CAT EAT WATfirst -
first -
Empty List
Deconstruct a Linked Lists 由於 Linked Lists 的 Node 是透過 new 配置的,
所以必須於解構子中以 delete 收回,以避免 memory leak 的問題。
二個方法 直接刪除
必須依序將每一個節點刪除,切不可以直接 delete first. Free Pool
不刪除節點,將這些欲收回的節點組織成一個 available-space list or av list ( 資料成員 static ListNode<Type> *av)
往後新增節點時,先檢查 Free Pool ,若 Free Pool 不為空,則從 Free Pool 取出一個節點配置出去,反之,若 Free Pool 為空,才 new 一個新的空節點或停止配置空間。
Free Pool 使 Liked Lists 的解構動作於常數時間完成。
Deconstruct a Linked Lists
直接刪除節點template <class Type>List<Type>::~List()//Free all nodes in the chain{ListNode<Type>* next;for (; first; first = next) {
next = first->link;delete first;
}}
Time Complexity O(n)
Deconstruct a Linked Lists
Free Pool
first
0av
second(1)
(2)
av = second
(3)(4)
= 0
Doubly Linked Lists
To efficiently delete a node, we need to know its preceding node. Therefore, doubly linked list is useful.
A node in a doubly linked list has at least three fields: left link field (llink), a data field (item), and a right link field (rlink).
Doubly Linked Listsclass DblList;class DblListNode{friend class DblList;private: int data; DblListNode *llink, *rlink;};
class DblList{public://List manipulation operationsprivate: DblListNode *first; //points to head node};
Doubly Linked Lists
BAT CAT EAT
-
p->llink->rlink == p == p->rlink->llink
dataLeftLink RightLink
first
-first
Empty doubly linked circular list with head node
Doubly Linked Lists: Delete
void DblList::Delete(DblListNode *x){ if (x==first) cerr<<“Deletion of head node not permitted”<<endl; else { x->llink->rlink = x->rlink; x->rlink->llink = x->llink; } }
CAT
-first
x
Doubly Linked Lists: Insert
-first
x
void DblList::Insert(DblListNode *p,DblListNode *x)//insert node p to the right of node x{ p->llink = x; p->rlink = x->rlink; x->rlink->llink = p; x->rlink = p;}
p
Generalized List Generalized List
A generalized list, A, is a finite sequence of n>= 0 elements, a0,…,an-1, where ai is either an atom or a list.
The elements ai, 0 i n-1, that are not atoms are said to be sub≦ ≦lists of A.
Examples D=() A= (a, (b, c)) B= (A, A, ()) C= (a, C)
Consequences Lists may be empty (Example D) lists may be shared by other lists (Example B) lists may be recursive (Example C)
Generalized ListD=0
a 0F TA
bF c 0F
T TB 0 0T
a 0F TC
D=()A= (a, (b, c))B= (A, A, ())C= (a, C)
Important Generalized List Functions List Copy
See textbook pp225-227 Program 4.36
List Equality See textbook pp228 Program 4.37
List Depth See textbook pp229 Program 4.38
Lists Copy 串列有兩種拷貝的方式:
淺拷貝( shallow copy ):不拷貝資料項目 深拷貝( deep copy ):拷貝資料項目
20 45 51 76
L
20 45 51 76
20 45 51 76
L
L’
淺拷貝
深拷貝
L’
List Copy with Recursive Algorithms Indirect Recursive A recursive algorithm consists of two
components: The recursive function (the workhorse);
Declared as a private function A second function that invokes the recursive function
at the top level (the driver); declared as a public function.
List Copyvoid GenList::Copy(const GenList& l){
first = Copy(l.first);}
GenListNode* GenList::Copy(GenListNode *p)//Copy the nonrecursive list with no shared sublists pointed at by p
{GenListNode *q = 0;if (p) {
q = new GenListNode;q->tag = p->tag;if (!p->tag)
q->data = p->data;else
q->dlink = Copy(p->dlink);q->link = Copy(p->link);
}return q;
}
Driver
Workhorse
O(M)
Example: List Copy A (Generalized Lists)
t
f a f b 0
t 0
t
f c
f e 0
f d 0
b
s
r
u
w
v
x
t
A
A((a,b),((c,d),e))
Example: List Copy A (Generalized Lists)
Level of recursion
Value of p Continuing level
p Continuing level
p
1 b 2 r 3 u
2 s 3 u 4 v
3 t 4 w 5 0
4 0 5 x 4 v
3 t 6 0 3 u
2 s 5 x 2 r
1 b 4 w 3 0
2 r
1 b
GenList::Copy(A)
List Depth
The Depth of list is defined as follows.
An empty list has depth 0.
1),,,()}(,),(max{1
0)(
11 nxxlisttheissifxdepthxdepth
atomanissifsdepth
nn
Heterogeneous list
A heterogeneous list is one that contains nodes of different types. If merging nodes by using union, then each node is allocate
d for the largest node type. This would waste space. Use of public inheritance and virtual functions can resolve t
his issue. Let S(x) denote the space occupied by an object of t
ype x, thenS(CombinedNode)=S(Data)+S(CombineNode *)
=S(int) + max(S(char), S(int), S(float)) + S(CombineNode *)
Heterogeneous list with unionstruct Data{ // id = 0, 1, or 2 if the node contains a char, an int, or a float
int id; union {
int i;char c;float f;
};};
class CombinedNode//Use union to merge different node types into one class definition{friend class List;friend class ListIterator;private:
Data data;CombinedNode *link;
};
Space allocation is based on the largest data type, which is float.
Heterogeneous list with unionclass list{ friend class ListIterator; public:
// List manipulation operations follow . private:
CombinedNode *first;};
//the return type of class ListIterator is Data*
Heterogeneous list with Public Inheritanceclass Node {
friend class List; friend class ListIterator;protected:
Node *link;virtual Data GetData() = 0;
};
template<class Type>class DerivedNode: public Node {
friend class List; friend class ListIterator;public:
DerivedNode(Type item): data(item) {link = 0;};private:
Type data;Data GetData();
};
Data DerivedNode<char>::GetData(){
Data t; t.id = 0; t.c = data; return t;}
Heterogeneous list with Public Inheritance
class List {friend class ListIterator;public:
Node *first;};
class ListIterator {public:
ListIterator(const List & l); list(l), current(l.first){ };Data* First(); // minor change in homogeneous list implementationData* Next(); // minor change in homogeneous list implementationBoolean NotNull(); // implemented as for homogeneous listsBoolean NextNotNull(); // implemented as for homogeneous lists
private:const List& list;Node* current;Data temp;
};
Key point using the dynamic typing through public inheritance, a
pointer to a Node* may be used to point to nodes of type DerivedNode<char> DerivedNode<int> DerivedNode<float>.
This eliminates the problem that necessitated the artificial union of the different node types
Heterogeneous list with Public Inheritance
Example
Stacks and Queues Polynomial Equivalence Classes Sparse Matrix
Example: Stacks and Queues
top
0
data link
0
first rear
Linked Queue
Linked Stack
data link
Example: Stacks and Queuesclass stack; //forward declarationclass StackNode {friend class stack;private: int data; StackNode *link; // 想想看,為何建構子是私有的? StackNode(int d=0, StackNode *l=0):data(d), link(l) {};};
class Stack{public: Stack() { top=0; }; //constructor void Add(const int); int *Delete(int &);private: StackNode *top; void StackEmpty(); };
其他的請看 textbook pp188-189
Example: Polynomial
3 14 2 8 1 0 0a.first
8 14 -3 10 10 6 0b.first
Polynomial representation of 3x14+2x8+1
Polynomial representation of 8x14-3x10+10x6
Polynomial representation of 3x14+2x8+1 with Circular linked lists
3 14 2 8 1 0c.first
Example: Polynomial
3 14 2 8 1 0first - -
first - -
Zero polynomial with dummy head to avoid special case
3x14+2x8+1 with dummy head to avoid special case
Example: Polynomial
struct Term// all members of Terms are public by default{
int coef; // coefficientint exp; // exponentvoid Init(int c, int e) {coef = c; exp = e;};
};
class Polynomial{ friend Polynomial operator+(const Polynomial&,const Polynomial&); private:
List<Term> poly;};
注意觀察, class Polynomial 如何運用之前所定義的 class List !
Example: PolynomialRepresentation of 3x2y with Generalized Lists
var y 0 ptr 1 0
var x 0 no 3 2 0P
trio vble exp link
trio vble exp link
About class definition of polynomial with Generalized ListsPlease see book pp222-223
Example: Polynomial with Generalized Lists trio == var: the node is a head node.
vble indicates the name of the variable. Or it is an integer point to the variable in a variable table.
exp is set to 0. trio == ptr
coefficient itself is a list and is pointed by the field dlink. exp is the exponent of the variable on which the list is base
d on. trio == no
coefficient is an integer and is stored in coef. exp is the exponent of the variable on which the list is base
d on.
Example: PolynomialRepresentation of P(x,y,z) with Generalized Lists
v z 0 p 2 p 1 0
v y 0 v y 0p 3 p 2 0 p 4 p 1 0
v x 0
v x 0
n 1 10
n 3 8 0
n 2 8 0
v x 0 n 2 0 0
v x 0 n 1 4 n 6 3 0
P(x,y,z) = x10y3z2 + 2x8y3z2 + 3x8y2z2 +x4y4z +6x3y4z +2yz= ((x10+2x8)y3 + 3x8y2)z2 + ((x4+6x3)y4+2y)z
Example: Equivalence Classes Equivalence Relation
Definition
A relation ≡ over a set S, is said to be an equivalence relation over S if and only if it is Reflexive (反身性) x≡x Symmetric (對稱性) x≡y y≡x Transitive (遞移性) x≡y and y≡z x≡z
over S.
Example = is an equivalence relation over Z (how prove? )
Example: Equivalence Classes Give a set S={0,1,2,3,4,5,6,7,8,9,10,11} and
define the relation ≡ as follows:0≡4, 3≡1, 6≡10, 8≡9, 7≡4, 6≡8, 3≡5, 2≡11, 11≡0
If ≡ is a equivalence relation over S, then we get partitioning of S into three equivalence classes:
{0,2,4,7,11}; { 1,3,5}; {6,8,9,10}; How do we determine the equivalence classes
over S?
Determine the Equivalence Classes Two phases to determine equivalence classe
s. Phase one
the equivalence pairs (i, j) are read in and stored. 讀入後如何表示這些關係?
Phase two Begin at 0 and find all pairs of the form (0, j). Continue until the entire equivalence class containing 0
has been found, marked, and printed. Next find another object not yet output, and repeat the a
bove process
Example: Equivalence Classes
[0]
[1]
[2]
[3]
[4]
[5]
[6]
[7]
[8]
[9]
[10]
[11]
11
40
30
110
5
10
00
7 30
8
100
40
6
90
80
60
0
20
datalink
datalink
Example: Sparse Matrix
Circular linked list representation of a sparse matrix has two types of nodes: head node: head, down, right, and next entry node: head, down, row, col, right, value
Head node i is the head node for both row i and column i.
Each head node is belonged to three lists: a row list, a column list, and a head node list.
For an nxm sparse matrix with r nonzero terms, the number of nodes needed is max{n, m} + r + 1.
Example: Sparse Matrix
4 4
0 2
1 0
2 1
3 3
-4
12
11
-15
H0
H1
H2
H3
H0 H1 H2 H3Matrix head
down head rightnext
Head node
value
down head row col right
Typical node
f i j
Setup for aij
注意: head data member of a node is not shown
Example: Sparse Matrix
15000
0040
00012
01100
A 4x4 sparse matrix
top related