List, (dynamic) linked list Let’s first forget about ‘classes’, but only a dynamic list. We make lists with ‘classes’ afterwards.

Slides:



Advertisements
Similar presentations
Chapter 4 Linked Lists. © 2005 Pearson Addison-Wesley. All rights reserved4-2 Preliminaries Options for implementing an ADT List –Array has a fixed size.
Advertisements

DATA STRUCTURES USING C++ Chapter 5
Circular Linked List. COMP104 Circular Linked List / Slide 2 Circular Linked Lists * A Circular Linked List is a special type of Linked List * It supports.
 A queue is a waiting line…….  It’s in daily life:-  A line of persons waiting to check out at a supermarket.  A line of persons waiting.
Doubly Linked List. COMP104 Doubly Linked Lists / Slide 2 Doubly Linked Lists * In a Doubly Linked List each item points to both its predecessor and successor.
Linked Lists
Programming Linked Lists. COMP104 Linked Lists / Slide 2 Motivation * A “List” is a useful structure to hold a collection of data. n Currently, we use.
Dynamic Objects. COMP104 Dynamic Objects / Slide 2 Memory Management * Static Memory Allocation n Memory is allocated at compiling time * Dynamic Memory.
List as an Abstract Data Type. struct Node{ public: int data; Node* next; }; typedef Node* Nodeptr; class List { public: List(); // constructor List(const.
Classes with dynamic members. int x; void f() { x=10; } main() { x=0; f(); } ‘Class’ matters! int x; void f() { int x; x=10; } main() { x=0; f(); } class.
Dynamic Objects. COMP104 Dynamic Objects / Slide 2 Memory Management * Static Memory Allocation n Memory is allocated at compilation time * Dynamic Memory.
Pointers and dynamic objects COMP171 Fall Pointers and dynamic objects/ Slide 2 Topics * Pointers n Memory addresses n Declaration n Dereferencing.
Abstract Data Type Example l One more example of ADT: l integer linked list using class l A class with dynamic objects: l Copy constructor l Destructor.
Review of pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
Concept of lists and array implementations of lists.
List as an Abstract Data Type. struct Node{ public: int data; Node* next; }; typedef Node* Nodeptr; class list { public: list(); // constructor list(const.
COMP103 - Linked Lists (Part A)1 Chapter 17 Truly dynamic memory management.
Linked Lists. COMP104 Lecture 33 / Slide 2 Linked Lists: Basic Idea * Data may be stored consecutively in a linked list. * Each element of the linked.
Abstract Data Type: List (optional, not required).
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 17 Linked.
Review on linked lists. Motivation * A “List” is a useful structure to hold a collection of data. n Currently, we use arrays for lists * Examples: List.
Chapter 4 Linked Lists. © 2005 Pearson Addison-Wesley. All rights reserved4-2 Preliminaries Options for implementing an ADT List –Array has a fixed size.
Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 Linked List and Namespace ~ include dynamic objects.
Classes with dynamic objects List as a (dynamic) class.
Doubly Linked List. COMP104 Doubly Linked Lists / Slide 2 Motivation * Doubly linked lists are useful for playing video and sound files with “rewind”
Chapter 4 Linked Lists. © 2005 Pearson Addison-Wesley. All rights reserved4-2 Preliminaries Options for implementing an ADT List –Array has a fixed size.
2 Preliminaries Options for implementing an ADT List Array has a fixed size Data must be shifted during insertions and deletions Linked list is able to.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
List, (dynamic) linked list Let’s first forget about ‘classes’, but only a dynamic list. We make lists with ‘classes’ afterwards.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 4: Linked Lists Data Abstraction & Problem Solving with.
1 CSC 211 Data Structures Lecture 21 Dr. Iftikhar Azim Niaz 1.
D ATA S TRUCTURE Ali Abdul Karem Habib MSc.IT. P OINTER A pointer is a variable which represents the location of a data item. We can have a pointer to.
Pointers OVERVIEW.
A first look an ADTs Solving a problem involves processing data, and an important part of the solution is the careful organization of the data In order.
1 Chapter 16 Linked Structures Dale/Weems. 2 Chapter 16 Topics l Meaning of a Linked List l Meaning of a Dynamic Linked List l Traversal, Insertion and.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 16. Linked Lists.
Lists Chapter 8. 2 Linked Lists As an ADT, a list is –finite sequence (possibly empty) of elements Operations commonly include: ConstructionAllocate &
Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 17: Linked Lists.
APS105 Lists. Structures Arrays allow a collection of elements –All of the same type How to collect elements of different types? –Structures; in C: struct.
Linked lists. Data structures to store a collection of items Data structures to store a collection of items are commonly used Typical operations on such.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
CS162 - Topic #7 Lecture: Dynamic Data Structures –Review of pointers and the new operator –Introduction to Linked Lists –Begin walking thru examples of.
Data Structures AZHAR MAQSOOD NUST Institute of Information Technology (NIIT) Lecture 6: Linked Lists Linked List Basics.
1 Linked List. Outline Introduction Insertion Description Deletion Description Basic Node Implementation Conclusion.
Data Structure & Algorithms
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.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
1 CMPT 117 Linked Lists (singly linked). 2 Problems with arrays  When an element is deleted from or inserted into an array, the rest of the array has.
CC 215 DATA STRUCTURES LINKED LISTS Dr. Manal Helal - Fall 2014 Lecture 3 AASTMT Engineering and Technology College 1.
Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part R2. Elementary Data Structures.
1 Linked List. List vs Arrays Two built-in data structures that can be used to organize data, or to create other data structures: Lists Arrays.
Programming Circular Linked List.
Exercise 1 From Lec80b-Ponter.ppt.
Chapter 4 Linked Lists.
CSCE 210 Data Structures and Algorithms
Chapter 4 Linked Lists
Summary on linked lists
Chapter 16-2 Linked Structures
as an abstract data structure and
Chapter 4 Linked Lists.
Pointers and dynamic objects
Chapter 4 Linked Lists.
Chapter 16 Linked Structures
Dynamic Objects.
Linked Lists.
List as an Abstract Data Type
Pointers and dynamic objects
Dynamic Objects.
Presentation transcript:

List, (dynamic) linked list Let’s first forget about ‘classes’, but only a dynamic list. We make lists with ‘classes’ afterwards.

A simple list Example: using a dynamic array * concept of a list, e.g. a list of integers n Print out info n Empty test n Search an element n Insertion (at head, at end, any position) n Deletion n … * implemented n by a static array (over-sized if necessary) int list[1000]; int size; n by a dynamic array int list[size]; int size; n by a linked list and more …

int main() { cout << "Enter list size: "; int n; cin >> n; int* A = new int[n]; initialize(A, n, 0); print(A, n); A = addEnd(A,n,5); print(A, n); A = addHead(A,n,5); print(A, n); A = deleteFirst(A,n); print(A, n); selectionSort(A, n); print(A, n); delete [] A; } How to use a list? int A[10000]; int n; Nothing compulsory in programming, only style matters!

Initialize void initialize(int list[], int size, int value){ for(int i=0; i<size; i++) list[i] = value; }

void print(int list[], int size) { cout << "[ "; for(int i=0; i<size; i++) cout << list[i] << " "; cout << "]" << endl; } Print out a list

Delete the first element // for deleting the first element of the array int* deleteFirst(int list[], int& size){ int* newList; newList = new int[size-1]; // make new array if(size){// copy and delete old array for(int i=0; i<size-1; i++) newList[i] = list[i+1]; delete [] list; } size--; return newList; }

Instead of A = deleteFirst(A,n) we can also just deleteFirst(A,n) if we define as a void type function: void deleteFirst(int*& A, int& size) { … A = newList; } Remark: We can also B = deleteFirst(A,n) if we keep the original intact

Adding Elements // for adding a new element to end of array int* addEnd(int list[], int& size, int value){ int* newList; newList = new int [size+1]; // make new array if(size){// copy and delete old array for(int i=0; i<size; i++) newList[i] = list[i]; delete [] list; } newList[size] = value; size++; return newList; }

// for adding a new element at the beginning of the array int* addHead(int list[], int& size, int value){ int* newList; newList = new int [size+1]; // make new array if(size){// copy and delete old array for(int i=0; i<size; i++) newList[i+1] = list[i]; delete [] list; } newList[0] = value; size++; return newList; } Add at the beginning:

Linked list: a dynamic list

Motivation * list using static array int myArray[1000]; int n; We have to decide (to oversize) in advance the size of the array (list) * list using dynamic array int* myArray; int n; cin >> n; myArray = new int[n]; We allocate an array (list) of any specified size while the program is running * linked-list (dynamic size) size = ?? The list is dynamic. It can grow and shrink to any size.

Array naturally represents a (ordered) list, the link is implicit, consecutive and contiguous! Now the link is explicit, any places! Data Link Data Link Data Link array linked list

Linked Lists: Basic Idea * A linked list is an ordered collection of data * Each element of the linked list has n Some data n A link to the next element * The link is used to chain the data Example: A linked list of integers: Data Link

* The list can grow and shrink Linked Lists: Basic Ideas addEnd(75), addEnd(85) deleteEnd(85), deleteHead(20), deleteHead(45) 75

* Original linked list of integers: * Insertion (in the middle): * Deletion (in the middle) Linked Lists: Operations old value deleted item

struct Node{ int data; Node* next; }; We can also: typedef Node* NodePtr; Definition of linked list type:

Linked List Structure * Node : Data + Link n Definition struct Node { int data;//contains useful information Node* next;//points to next element or NULL }; n Create a Node Node* p; p = new Node;//points to newly allocated memory n Delete a Node delete p;

n Access fields in a node (*p).data;//access the data field (*p).next;//access the pointer field Or it can be accessed this way p->data//access the data field p->next//access the pointer field

Representing and accessing linked lists * We define a pointer Node* head; that points to the first node of the linked list. When the linked list is empty then head is NULL Head

Passing a Linked List to a Function  When passing a linked list to a function it should suffice to pass the value of head. Using the value of head the function can access the entire list.  Problem: If a function changes the beginning of a list by inserting or deleting a node, then head will no longer point to the beginning of the list.  Solution: When passing head always pass it by reference (not good!) or using a function to return a new pointer value It is roughly the same as for an array!!!

Implementation of an (Unsorted) Linked List

Start the first node from scratch Node* newPtr; newPtr = new Node; newPtr->data = 20; newPtr->next = NULL; head = newPtr; Head newPtr 20 Head head = NULL;

Inserting a Node at the Beginning newPtr = new Node; newPtr->data = 13; newPtr->next = Head; head = newPtr; Head newPtr 13 20

Keep going … Head newPtr

void addHead(Node*& head, int newdata){ Node* newPtr = new Node; newPtr->data = newdata; newPtr->next = Head; head = newPtr; } Adding an element to the head: Call by reference, scaring!!! NodePtr&

Node* addHead(Node* head, int newdata){ Node* newPtr = new Node; newPtr->data = newdata; newPtr->next = Head; return newPtr; } Also written (more functionally) as: Compare it with ‘addHead’ with a dynamic array implementation

(to delete) Deleting the Head Node Node* p; p = head; head = head->next; delete p; head p

void deleteHead(Node*& head){ if(head != NULL){ NodePtr p = head; head = head->next; delete p; } Node* deleteHead(Node* head){ if(head != NULL){ NodePtr p = head; head = head->next; delete p; } return head; } As a function:

Displaying a Linked List p = head; p = p->next; 2045 head p 2045 head p

void displayList(Node* head){ NodePtr p; p = head; while(p != NULL){ cout data << endl; p = p->next; } A linked list is displayed by walking through its nodes one by one, and displaying their data fields (similar to an array!). void displayArray(int data[], int size) { int n=0; while ( n<size ) { cout << data[i] << endl; n++; } For an array:

//return the pointer of the node that has data=item //return NULL if item does not exist Node* searchNode(Node* head, int item){ NodePtr p = head; NodePtr result = NULL; bool found=false; while((p != NULL) && (!found)){ if(p->data == item) { found = true; result = p;} p = p->next; } return result; } Searching for a node (look at array searching first!)

void main() { const int size=8; int data[size] = { 10, 7, 9, 1, 17, 30, 5, 6 }; int value; cout << "Enter search element: "; cin >> value; int n=0; int position=-1; bool found=false; while ( (n<size) && (!found) ) { if(data[n] == value) { found=true; position=n;} n++; } if(position==-1) cout << "Not found!!\n"; else cout << "Found at: " << position << endl; } Remember array searching algorithm: It is essentially the same!

Variations of linked lists * Unsorted linked lists * Sorted linked lists * Circular linked lists * Doubly linked lists * …

Further considerations for the unsorted lists: * Physical copy of list for operators like ‘deleteHead’ and ‘addHead’ * ‘deleteHead’ should be understood as a decomposition into a sub-list …

Node* deleteHead(Node* head){ // physically copy head into a new one, newhead // so to keep the original list intact! Node* newhead=NULL; Node* temp=head; while(temp!=NULL) { newhead=addEnd(newhead,temp->data); temp=temp->next; } if(newhead != NULL){ Node* p = newhead; newhead = newhead->next; delete p; } return newhead; } B = deleteHead(A);

* Original linked list of integers: * Add to the end (insert at the end): More operation: adding to the end Last element The key is how to locate the last element or node of the list!

void addEnd(NodePtr& head, int newdata){ NodePtr newPtr = new Node; newPtr->data = newdata; newPtr->next = NULL; NodePtr last = head; if(last != NULL){ // general non-empty list case while(last->next != NULL) last=last->next; last->next = newPtr; } else// deal with the case of empty list head = newPtr; } Add to the end: Link new object to last->next Link a new object to empty list

NodePtr addEnd(NodePtr head, int newdata){ NodePtr newPtr = new Node; newPtr->data = newdata; newPtr->next = NULL; NodePtr last = head; if(last != NULL){ // general non-empty list case while(last->next != NULL) last=last->next; last->next = newPtr; } else// deal with the case of empty list head = newPtr; return head; } Add to the end as a function:

Implementation of a Sorted Linked List

Inserting a Node Head cur prev... newPtr 1.(a) Create a new node using: NodePtr newPtr = new node; (b) Fill in the data field correctly. 2. Find “prev” and “cur” such that the new node should be inserted between *prev and *cur. 3. Connect the new node to the list by using: (a) newPtr->next = cur; (b) prev->next = newPtr;

Finding prev and cur Suppose that we want to insert or delete a node with data value newValue. Then the following code successfully finds prev and cur such that prev->data data

prev = NULL; cur = head; found=false; while( (cur!=NULL) && (!found) ) { if (newValue > cur->data) { prev=cur; cur=cur->next; } else found = true; } Prev is necessary as we can’t go back! It’s a kind of search algo,

prev = NULL; cur = head; while( (cur!=NULL) && (newValue>cur->data) ) { prev=cur; cur=cur->next; } Logical AND (&&) is short-circuited, sequential, i.e. if the first part is false, the second part will not be executed. Finally, it is equivalent to:

//insert item into linked list according to ascending order Node* insertNode(Node* head, int item){ NodePtr newp, cur, pre; newp = new Node; newp->data = item; pre = NULL; cur = head; while( (cur != NULL) && (item>cur->data)){ pre = cur; cur = cur->next; } if(pre == NULL){//insert to head of linked list newp->next = head; head = newp; } else { pre->next = newp; new->next = cur; } return head; } If the position happens to be the head General case

// not recommended void type function void insertNode(NodePtr& head, int item){ NodePtr newp, cur, pre; newp = new Node; newp->data = item; pre = NULL; cur = head; while( (cur != NULL) && (item>cur->data)){ pre = cur; cur = cur->next; } if(pre == NULL){//insert to head of linked list newp->next = head; head = newp; } else { pre->next = newp; new->next = cur; }

(to delete) Deleting a Node * To delete a node from the list 1. Locate the node to be deleted (a) cur points to the node. (b) prev points to its predecessor 2. Disconnect node from list using: prev->next = cur->next; 3. Return deleted node to system: delete cur; Head cur prev...

Node* deleteNode(Node* head, int item){ NodePtr prev=NULL, cur = head; while( (cur!=NULL) && (item > cur->data)){ prev = cur; cur = cur->next; } if ( cur!==NULL && cur->data==item) { if(cur==head) head = head->next; else prev->next = cur->next; delete cur; } return head; } Delete an element in a sorted linked list: If the element is at the head General case We can delete only if the element is present! If (cur==NULL || cur->data!=item) Item is not in the list! Get the location

void deleteNode(NodePtr& head, int item){ NodePtr prev=NULL, cur = head; while( (cur!=NULL) && (item > cur->data)){ prev = cur; cur = cur->next; } if ( cur!==NULL && cur->data==item) { if(cur==Head) Head = Head->next; else prev->next = cur->next; delete cur; } // in a void function, not recommended If the element is at the head General case We can delete only if the element is present! If (cur==NULL || cur->data!=item) Item is not in the list! Get the location