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

Slides:



Advertisements
Similar presentations
Linked Lists Geletaw S..
Advertisements

Pointers.
COMP171 Fall 2005 Lists.
Linked Lists.
Data Structures ADT List
DATA STRUCTURES USING C++ Chapter 5
Chapter 3 – Lists A list is just what the name implies, a finite, ordered sequence of items. Order indicates each item has a position. A list of size 0.
Linked List 1. Introduction to Linked List 2. Node Class 3. Linked List 4. The Bag Class with Linked List.
Linked Lists CENG 213 Data Structures.
Chapter 17 Linked List Saurav Karmakar Spring 2007.
Review Learn about linked lists
Data Structures: A Pseudocode Approach with C
Linked Lists Compiled by Dr. Mohammad Alhawarat CHAPTER 04.
Linked Lists
1 Chapter 3 Arrays, Linked Lists, and Recursion. 2 Static vs. Dynamic Structures A static data structure has a fixed size This meaning is different than.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 17: Linked Lists.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.
C++ Programming: Program Design Including Data Structures, Fifth Edition Chapter 17: Linked Lists.
Data Structures Using C++ 2E
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Custom Templatized Data Structures.
Linked Lists list elements are stored, in memory, in an arbitrary order explicit information (called a link) is used to go from one element to the next.
1 CSC 211 Data Structures Lecture 21 Dr. Iftikhar Azim Niaz 1.
Data Structures Using Java1 Chapter 4 Linked Lists.
Linked Lists part 2 CS 244 Brent M. Dingle, Ph.D. Game Design and Development Program Department of Mathematics, Statistics, and Computer Science University.
Lists II. List ADT When using an array-based implementation of the List ADT we encounter two problems; 1. Overflow 2. Wasted Space These limitations are.
1 Linked-list, stack and queue. 2 Outline Abstract Data Type (ADT)‏ Linked list Stack Queue.
Dynamic Array. An Array-Based Implementation - Summary Good things:  Fast, random access of elements  Very memory efficient, very little memory is required.
Lists Chapter 8. 2 Linked Lists As an ADT, a list is –finite sequence (possibly empty) of elements Operations commonly include: ConstructionAllocate &
Data Structures Using C++1 Chapter 5 Linked Lists.
1 String Processing CHP # 3. 2 Introduction Computer are frequently used for data processing, here we discuss primary application of computer today is.
M180: Data Structures & Algorithms in Java Linked Lists Arab Open University 1.
Data Structures. Abstract Data Type A collection of related data is known as an abstract data type (ADT) Data Structure = ADT + Collection of functions.
Chapter 5 Linked List by Before you learn Linked List 3 rd level of Data Structures Intermediate Level of Understanding for C++ Please.
Engineering Classes. Objectives At the conclusion of this lesson, students should be able to: Explain why it is important to correctly manage dynamically.
Chapter 17: Linked Lists. Objectives In this chapter, you will: – Learn about linked lists – Learn the basic properties of linked lists – Explore insertion.
Data Structure and Algorithms
Linked List.  Is a series of connected nodes, where each node is a data structure with data and pointer(s) Advantages over array implementation  Can.
1 Linked List. Outline Introduction Insertion Description Deletion Description Basic Node Implementation Conclusion.
Data Structure & Algorithms
CSCS-200 Data Structure and Algorithms Lecture
1 Linked List. 2 List A list refers to a sequence of data items  Example: An array The array index is used for accessing and manipulation of array elements.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 17: Linked Lists.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 18: Linked Lists.
Linked Lists Data Structures and Algorithms CS 244 Brent M. Dingle, Ph.D. Department of Mathematics, Statistics, and Computer Science University of Wisconsin.
CSC 243 – Java Programming, Spring, 2014 Week 4, Interfaces, Derived Classes, and Abstract Classes.
Data Structures and Algorithm Analysis Dr. Ken Cosh Linked Lists.
UNIT-II Topics to be covered Singly linked list Circular linked list
LINKED LISTS.
© Oxford University Press All rights reserved. Data Structures Using C, 2e Reema Thareja.
1 Data Organization Example 1: Heap storage management Maintain a sequence of free chunks of memory Find an appropriate chunk when allocation is requested.
Chapter 3 Lists, Stacks, Queues. Abstract Data Types A set of items – Just items, not data types, nothing related to programming code A set of operations.
Linked Lists Source: presentation based on notes written by R.Kay, A. Hill and C.Noble ● Lists in general ● Lists indexed using pointer arrays ● Singly.
Memory Management.
Chapter 16: Linked Lists.
Lecture 6 of Computer Science II
C++ Programming:. Program Design Including
Linked List :: Basic Concepts
Lectures linked lists Chapter 6 of textbook
Data Structure Interview Question and Answers
Review Deleting an Element from a Linked List Deletion involves:
Lists CS 3358.
DATA STRUCTURES AND OBJECT ORIENTED PROGRAMMING IN C++
Data Structures Interview / VIVA Questions and Answers
CSCI 3333 Data Structures Linked Lists.
Prof. Neary Adapted from slides by Dr. Katherine Gibson
Arrays and Linked Lists
Linked Lists.
Intro to OOP with Java, C. Thomas Wu By : Zanariah Idrus
Data Structures & Algorithms
17CS1102 DATA STRUCTURES © 2018 KLEF – The contents of this presentation are an intellectual and copyrighted property of KL University. ALL RIGHTS RESERVED.
Presentation transcript:

1 Data Structures for Media Linked Lists

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 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 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 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 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 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 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= dereferencing References References int count = 1; int &cRef = count; ++cRef; What is the value of count?

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 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 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 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 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 // 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 One case remaining for insert One case remaining for insert Dummy Header Node newnode …… p newnode …… p before insert after insert

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 One case remaining for remove One case remaining for remove before remove after remove …… p q p q Dummy Header Node

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 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 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 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 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 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 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 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 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 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