Linked Lists. Linked list: a collection of items (nodes) containing two components: Data Address (link) of the next node in the list

Similar documents
Linked Lists. Linked list: a collection of items (nodes) containing two components: Data Address (link) of the next node in the list

! A data structure representing a list. ! A series of dynamically allocated nodes. ! A separate pointer (the head) points to the first

! A data structure representing a list. ! A series of nodes chained together in sequence. ! A separate pointer (the head) points to the first

Ch. 17: Linked Lists. Introduction to Linked Lists

Chapter 17: Linked Lists

! A data type for which: ! An ADT may be implemented using various. ! Examples:

Chapter 17: Linked Lists

! A data structure representing a list. ! A series of nodes chained together in sequence. ! A separate pointer (the head) points to the first

Linked Lists. Gaddis Ch. 17. CS 2308 :: Spring 2016 Molly O'Neil

C++ is Fun Part 14 at Turbine/Warner Bros.! Russell Hanson

1 Short Answer (7 Points Each)

Dynamic Data Structures

CS 103 Unit 11. Linked Lists. Mark Redekopp

CS 103 Unit 15. Doubly-Linked Lists and Deques. Mark Redekopp

Linked List using a Sentinel

CS 103 Unit 11. Linked Lists. Mark Redekopp

Ashish Gupta, Data JUET, Guna

Lists, Stacks, and Queues. (Lists, Stacks, and Queues ) Data Structures and Programming Spring / 50

CSCE 110 PROGRAMMING FUNDAMENTALS

EE 355 Unit 11b. Doubly-Linked Lists and Deques. Mark Redekopp

BBM 201 DATA STRUCTURES

! Determine if a number is odd or even. ! Determine if a number/character is in a range. - 1 to 10 (inclusive) - between a and z (inclusive)

Cpt S 122 Data Structures. Course Review FINAL. Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive)

CA341 - Comparative Programming Languages

Data Structures (CS301) LAB

Abstract Data Types 1

Abstract Data Types 1

Data Structure Series

Abstract Data Types. CptS 223 Advanced Data Structures. Larry Holder School of Electrical Engineering and Computer Science Washington State University

What is recursion? Recursion. Recursive message() modified. How can a function call itself? contains a reference to itself. Week 10. Gaddis:

What is recursion? Recursion. How can a function call itself? Recursive message() modified. Week 10. contains a reference to itself.

Introduction to the Linked List ADT

Advanced Linked Lists. Doubly Linked Lists Circular Linked Lists Multi- Linked Lists

! A data type for which: ! An ADT may be implemented using various. ! Examples:

The time and space are the two measure for efficiency of an algorithm.

Lecture Notes CPSC 122 (Fall 2014) Today Quiz 7 Doubly Linked Lists (Unsorted) List ADT Assignments Program 8 and Reading 6 out S.

DATA STRUCTURES AND ALGORITHMS LECTURE 08 QUEUES IMRAN IHSAN ASSISTANT PROFESSOR AIR UNIVERSITY, ISLAMABAD

Standard Template Library

! Determine if a number is odd or even. ! Determine if a number/character is in a range. - 1 to 10 (inclusive) - between a and z (inclusive)

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

Spring 2008 Data Structures (CS301) LAB

1 Deletion in singly linked lists (cont d) 1 Other Functions. 1 Doubly Linked Lists. 1 Circular lists. 1 Linked lists vs. arrays

Data Structures. Alice E. Fischer. Lecture 4, Fall Alice E. Fischer Data Structures L4... 1/19 Lecture 4, Fall / 19

Cpt S 122 Data Structures. Data Structures

EECE.2160: ECE Application Programming

Linked List. April 2, 2007 Programming and Data Structure 1

CMSC 341 Lecture 7 Lists

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

Implementation. Learn how to implement the List interface Understand the efficiency trade-offs between the ArrayList and LinkedList implementations

Revision Statement while return growth rate asymptotic notation complexity Compare algorithms Linear search Binary search Preconditions: sorted,

LECTURE 03 LINKED LIST

CSCI-1200 Data Structures Fall 2013 Lecture 9 Iterators & Lists

Data Structures and Algorithms for Engineers

The combination of pointers, structs, and dynamic memory allocation allow for creation of data structures

Template based set of collection classes STL collection types (container types)

SSE2034: System Software Experiment 3

CS32 - Week 2. Umut Oztok. July 1, Umut Oztok CS32 - Week 2

5 Phases of Software Life Cycle

Purpose of Review. Review some basic C++ Familiarize us with Weiss s style Introduce specific constructs useful for implementing data structures

Higher National Diploma in Information Technology. First Year Second Semester Examination IT 2003-Data Structure and Algorithm.

CS 103 Unit 12 Slides

Data Structures and Algorithms for Engineers

Queue Implementations

Linked lists. Insert Delete Lookup Doubly-linked lists. Lecture 6: Linked Lists

CSCI-1200 Data Structures Fall 2017 Lecture 9 Iterators & STL Lists

CS183 Software Design. Textbooks. Grading Criteria. CS183-Su02-Lecture 1 20 May by Eric A. Durant, Ph.D. 1

Arrays and Linked Lists

First Examination. CS 225 Data Structures and Software Principles Spring p-9p, Tuesday, February 19

Linear Structures. Linear Structure. Implementations. Array details. List details. Operations 2/10/2013

CS32 Discussion Week 3

! Determine if a number is odd or even. ! Determine if a number/character is in a range. ! Assign a category based on ranges (wind speed)

CSE030 Fall 2012 Final Exam Friday, December 14, PM

Lab 2: Pointers. //declare a pointer variable ptr1 pointing to x. //change the value of x to 10 through ptr1

What is recursion? Recursion. How can a function call itself? Recursive message() modified. Week 10. contains a reference to itself. Gaddis:

Programming in C/C Lecture 2

EC8393FUNDAMENTALS OF DATA STRUCTURES IN C Unit 3

MIDTERM EXAMINATION Spring 2010 CS301- Data Structures

Jordan University of Science & Technology Department of Computer Science CS 211 Exam #1 (23/10/2010) -- Form A

CMPT 225. Lecture 6 linked list

CPSC 260 Data Structures and Algorithms for Computer Engineers Linked Lists!

University of Waterloo Department of Electrical and Computer Engineering ECE 250 Data Structures and Algorithms. Final Examination

+ Abstract Data Types

Introduction to Linked List: Review. Source:

Linear Structures. Linear Structure. Implementations. Array details. List details. Operations 4/18/2013

FINALTERM EXAMINATION Fall 2009 CS301- Data Structures Question No: 1 ( Marks: 1 ) - Please choose one The data of the problem is of 2GB and the hard

Object Oriented Programming COP3330 / CGS5409

FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- MARCH, 2012 DATA STRUCTURE (Common to CT and IF) [Time: 3 hours

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

Lists (Section 5) Lists, linked lists Implementation of lists in C Other list structures List implementation of stacks, queues, priority queues

CSCI-1200 Data Structures Fall 2014 Lecture 8 Iterators

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR

Linked Lists. Contents. Steven J. Zeil. July 31, Linked Lists: the Basics 4

STL: C++ Standard Library

A linked list. Subtopic: Linked lists. List-node structure type. Array implementation of a linked list. Inserting into a sorted collection

[CSE10200] Programming Basis ( 프로그래밍기초 ) Chapter 9. Seungkyu Lee. Assistant Professor, Dept. of Computer Engineering Kyung Hee University

CSCE 110 PROGRAMMING FUNDAMENTALS

Iterators. node UML diagram implementing a double linked list the need for a deep copy. nested classes for iterator function objects

lecture09: Linked Lists

CS427 Inheritance and Virtual Functions. Linked lists. 2/27. 01Replacement.cpp link! i n t GetY ( void ) { return ( y ) ; } ;

Transcription:

Linked Lists Introduction : Data can be organized and processed sequentially using an array, called a sequential list Problems with an array Array size is fixed Unsorted array: searching for an item is slow Sorted array: insertion and deletion is slow because it requires data movement Linked list: a collection of items (nodes) containing two components: Data Address (link) of the next node in the list Fall 2018 Husain Gholoom Lecturer in Computer Science Page 1

Introduction to Linked Lists A singly linked list is a concrete data structure consisting of a sequence of nodes. It is data structure representing a list or a sequence of items that can only be accessed in order (that is, from first to last) A series of nodes chained together in sequence. Each node stores an element and a link to the next node Data items are stored in nodes, and each node contains a pointer to the next node A separate pointer (the head) points to the first item in the list. The last element points to nothing (NULL) Fall 2018 Husain Gholoom Lecturer in Computer Science Page 2

Linked List and Values of the List Example: linked list with four nodes Fall 2018 Husain Gholoom Lecturer in Computer Science Page 3

current = head; Copies value of head into current ; List after the statement current = head ; executes Fall 2018 Husain Gholoom Lecturer in Computer Science Page 4

current = current->link; List after the statement current = current -> link ; executes Fall 2018 Husain Gholoom Lecturer in Computer Science Page 5

Basic Operations on Linked Lists: The nodes are dynamically allocated - The list grows and shrinks as nodes are added / removed. Linked lists can easily insert a node between other nodes ( insert ) Linked lists can easily delete a node from between other nodes ( remove ) Linked lists can easily retrieve an element at a certain position ( findkth) Linked lists can easily locate the position of an object in a list ( find ) Linked lists can easily print the list ( printlist ) Node Insertion Example : Assume that you have the following list insert a new node with info 50 after p in this list: Fall 2018 Husain Gholoom Lecturer in Computer Science Page 6

Suggested Steps Create New node, Store 50 in the new node Update the pointers Fall 2018 Husain Gholoom Lecturer in Computer Science Page 7

Node Deletion Example : Node with info 34 is to be deleted: Fine the node to be deleted. Then point its previous pointer to its next pointer. Delete the pointer s node p->link = p->link ->link; Fall 2018 Husain Gholoom Lecturer in Computer Science Page 8

Fall 2018 Husain Gholoom Lecturer in Computer Science Page 9

Variations of linked lists Singly linked list Circular linked lists Doubly linked lists The Abstract Data Type A sequence of zero or more elements A1, A2, A3, AN N: length of the list A1: first element AN: last element Ai: position i If N=0, then empty list Linearly ordered - Ai precedes Ai+1 - Ai follows Ai-1 Fall 2018 Husain Gholoom Lecturer in Computer Science Page 10

Implementation of an ADT Choose a data structure to represent the ADT - e.g. arrays, records, etc. Each operation associated with the ADT is implemented by one or more subroutines Two standard implementations for the list ADT - Array-based - Linked list Fall 2018 Husain Gholoom Lecturer in Computer Science Page 11

Array Implementation Elements are stored in contiguous array positions Uses an iterator to move cursor Has a fixed size Insert at position 0 (making a new element) requires first pushing the entire array down one spot to make room Delete at position 0 requires shifting all the elements in the list up one On average, half of the lists needs to be moved for either operation Requires an estimate of the maximum size of the list waste space - printlist and find: O(n) - findkth: O(1) - insert and delete: O(n) Fall 2018 Husain Gholoom Lecturer in Computer Science Page 12

Example : Array Implementation Let LA be a Linear Array (unordered) with N elements and K is a positive integer such that K<=N. Following is the algorithm where ITEM is inserted into the K th position of LA #include<iostream> using namespace std; int main() { int LA[] = { 1, 3, 5, 7, 8 ; int item = 10, k = 3, n = 5; // n is size, k is position int i = 0, j = n; cout << "The original array elements are :\n\n"; for (i = 0; i < n; i++) { cout << "LA[" << i << "] = " << LA[i] << endl; n = n + 1; while (j >= k) { LA[j + 1] = LA[j]; j = j - 1; LA[k] = item; cout << "\nthe array elements after insertion :\n\n"; for (i = 0; i < n; i++) { cout << "LA[" << i << "] = " << LA[i] << endl; Fall 2018 Husain Gholoom Lecturer in Computer Science Page 13

Sample Run The original array elements are : LA[0] = 1 LA[1] = 3 LA[2] = 5 LA[3] = 7 LA[4] = 8 The array elements after insertion : LA[0] = 1 LA[1] = 3 LA[2] = 5 LA[3] = 10 LA[4] = 7 LA[5] = 8 Fall 2018 Husain Gholoom Lecturer in Computer Science Page 14

Example - Insertion at the Beginning of an Array #include<iostream> using namespace std; int main() { int array[] = { 2, 3, 4, 5 ; int N = 4; // number of elements in array int i = 0; // loop variable // print array before insertion cout << "\nprinting array before insertion \n\n"; for (i = 0; i < N; i++) { cout << "array[" << i << "] = " << array[i] << endl; // now shift rest of the elements downwards for (i = N; i >= 0; i--) { array[i + 1] = array[i]; // add new element at first position array[0] = 1000; // increase N to reflect number of elements N = N + 1; // print to confirm cout << "\nprinting array after insertion \n\n"; for (i = 0; i < N; i++) { cout << "array[" << i << "] = " << array[i] << endl; Fall 2018 Husain Gholoom Lecturer in Computer Science Page 15

Sample Run Printing array before insertion array[0] = 2 array[1] = 3 array[2] = 4 array[3] = 5 Printing array after insertion array[0] = 1000 array[1] = 2 array[2] = 3 array[3] = 4 array[4] = 5 Fall 2018 Husain Gholoom Lecturer in Computer Science Page 16

Pointer Implementation (Linked List) Requires no estimate of the maximum size of the list - No wasted space printlist and find: O(n) findkth: O(n) insert and delete: O(1) - e.g. insert at position 0 (making a new element) Insert does not require moving the other elements - e.g. delete at position 0 requires no shifting of elements - Insertion and deletion becomes easier, but finding the Kth element moves from O(1) to O(n) Node Organization Each node contains: - Data field may be organized as a structure, an object, etc. - A pointer that can point to another node Fall 2018 Husain Gholoom Lecturer in Computer Science Page 17

Empty List An empty list contains 0 nodes. The list head points to NULL (address 0) (There are no nodes, it s empty) list head NULL Declaring the Linked List Data Type We will be defining a class for a linked list data type that can store values of type double. The data type will describe the values (the lists) and operations over those values. In order to define the values we must: Define a data type for the nodes Define a pointer variable (head) that points to the first node in the list. Fall 2018 Husain Gholoom Lecturer in Computer Science Page 18

Declaring the Node data type Use a struct for the node type : this is just a data type, no variables declared next can hold the address of a ListNode. - it can also be NULL - self-referential data structure struct ListNode { double value; ListNode *next; ; Defining the Linked List variable Define a pointer for the head of the list: ListNode *head = NULL; It must be initialized to NULL to signify the end of the list. Now we have an empty linked list: head NULL Fall 2018 Husain Gholoom Lecturer in Computer Science Page 19

Using NULL Equivalent to address 0. Used to specify end of the list. Use ONE of the following for NULL: #include <iostream> or #include <cstddef> To test a pointer for NULL (these are equivalent): while (p)... <==> while (p!= NULL)... if (!p)... <==> if (p == NULL)... Fall 2018 Husain Gholoom Lecturer in Computer Science Page 20

CS3358 - Data Structures So, in C++ The following are equivalent : ListNode *p = head; while ((*p).next!= NULL) p = (*p).next; ListNode *p = head; while (p->next) p = p->next; p=p->next is like i++ Fall 2018 Husain Gholoom Lecturer in Computer Science Page 21

Linked List operations Basic operations: create a new, empty list append a node to the end of the list insert a node within the list delete a node display the linked list delete/destroy the list Linked List class declaration // file NumberList.h class NumberList { private: struct ListNode // the node data type { double value; // data ListNode *next; // ptr to next node ; ListNode *head; // the list head public: NumberList(); ~NumberList(); ; void appendnode(double); void insertnode(double); void deletenode(double); void displaylist(); Fall 2018 Husain Gholoom Lecturer in Computer Science Page 22

Linked List functions: constructor Constructor: sets up empty list // file NumberList.cpp #include "NumberList.h" NumberList::NumberList() { head = NULL; Linked List functions: appendnode appendnode: adds new node to end of list Algorithm: Create a new node and store the data in it If the list has no nodes (it s empty) Make head point to the new node. else Find the last node in the list Make the last node point to the new node When defining list operations, always consider special cases: Empty list First element, front of the list (when head pointer is involved) Fall 2018 Husain Gholoom Lecturer in Computer Science Page 23

Linked List functions code : appendnode void NumberList::appendNode(double num) { ListNode *newnode; // To point to the new node // Create a new node and store the data in it newnode = new ListNode; newnode->value = num; newnode->next = NULL; // If list is empty, make head point to new node if (!head) head = newnode; else { ListNode *nodeptr; // To move through the list nodeptr = head; // initialize to start of list // traverse list to find last node while (nodeptr->next) //it s not last nodeptr = nodeptr->next; //make it pt to next // now nodeptr pts to last node // make last node point to newnode nodeptr->next = newnode; Fall 2018 Husain Gholoom Lecturer in Computer Science Page 24

Traversing and Displaying a Linked List Visit each node in a linked list, to - display contents, sum data, test data, etc. Basic process: set a pointer to point to what head points to while pointer is not NULL process data of current node go to the next node by setting the pointer to the pointer field of the current node end while Linked List functions code : displaylist void NumberList::displayList() { ListNode *nodeptr; //ptr to traverse the list // start nodeptr at the head of the list nodeptr = head; // while nodeptr pts to something (not NULL), continue while (nodeptr) { //Display the value in the current node cout << nodeptr->value << endl; //Move to the next node nodeptr = nodeptr->next; Fall 2018 Husain Gholoom Lecturer in Computer Science Page 25

Or the short version: void NumberList::displayList() { ListNode *nodeptr; for (nodeptr = head; nodeptr; nodeptr = nodeptr->next) cout << nodeptr->value << endl; Driver to demo NumberList ListDriver.cpp //ListDriver.cpp: using NumberList #include "NumberList.h" int main() { // Define the list NumberList list; // Append some values to the list list.appendnode(2.5); list.appendnode(7.9); list.appendnode(12.6); // Display the values in the list. list.displaylist(); return 0; Output: 2.5 7.9 12.6 Fall 2018 Husain Gholoom Lecturer in Computer Science Page 26

Deleting a Node from a Linked List deletenode: removes node from list, and deletes (deallocates) the removed node. Requires two pointers: - one to point to the node to be deleted - one to point to the node before the node to be deleted. Change the pointer of the previous node to point to the node after the one to be deleted. previousnode->next = nodeptr->next; Now just delete the nodeptr node delete nodeptr; Fall 2018 Husain Gholoom Lecturer in Computer Science Page 27

Delete Node Algorithm Delete the node containing num If list is empty, exit If first node is num make p point to first node make head point to second node delete p else use p to traverse the list, until it points to num or NULL --as p is advancing, make n point to the node before if (p is not NULL) make n s node point to what p s node points to delete p s node Fall 2018 Husain Gholoom Lecturer in Computer Science Page 28

Linked List functions: deletenode void NumberList::deleteNode(double num) { if (!head) // empty list, exit ( head == NULL ) return; ListNode *nodeptr; // to traverse the list if (head->value == num) { // if first node is num nodeptr = head; head = nodeptr->next; delete nodeptr; else { ListNode *previousnode; // trailing node pointer nodeptr = head; // traversal ptr, set to first node // skip nodes not equal to num, stop at last while (nodeptr && nodeptr->value!= num) { previousnode = nodeptr; // save it! nodeptr = nodeptr->next; // advance it if (nodeptr) { // num is found, set links + delete previousnode->next = nodeptr->next; delete nodeptr; // else: end of list, num not found in list, do nothing Fall 2018 Husain Gholoom Lecturer in Computer Science Page 29

Driver to demo NumberList ListDriver.cpp // set up the list NumberList list; list.appendnode(2.5); list.appendnode(7.9); list.appendnode(12.6); list.displaylist(); // Nice test case, checks all three cases cout << endl << "remove 7.9:" << endl; list.deletenode(7.9); list.displaylist(); cout << endl << "remove 8.9: " << endl; list.deletenode(8.9); list.displaylist(); cout << endl << "remove 2.5: " << endl; list.deletenode(2.5); list.displaylist(); Output: 2.5 7.9 12.6 remove 7.9: 2.5 12.6 remove 8.9: 2.5 12.6 remove 2.5: 12.6 Fall 2018 Husain Gholoom Lecturer in Computer Science Page 30

Destroying a Linked List The destructor must delete (deallocate) all nodes used in the list To do this, use list traversal to visit each node For each node, - Save the address of the next node in a pointer - Delete the node Linked List functions: destructor ~NumberList: deallocates all the nodes NumberList::~NumberList() { ListNode *nodeptr; // traversal ptr ListNode *nextnode; // saves the next node nodeptr = head; //start at head of list while (nodeptr) { nextnode = nodeptr->next; // save the next delete nodeptr; // delete current nodeptr = nextnode; // advance ptr Fall 2018 Husain Gholoom Lecturer in Computer Science Page 31

Inserting a Node into a Linked List Requires two pointers: - pointer to point to the node after the insertion point - pointer to point to node before point of insertion New node is inserted between the nodes pointed at by these pointers The before and after pointers move in tandem as the list is traversed to find the insertion point - Like delete Note that the insertnode implementation that follows assumes that the list is sorted. The insertion point is - immediately before the first node in the list that has a value greater than the value being inserted or - at the end if the value is greater than all items in the list. Not always applicable, but it is a good demonstration of inserting a node in the middle of a list. Fall 2018 Husain Gholoom Lecturer in Computer Science Page 32

Linked List functions: insertnode insertnode: inserts num into middle of list void NumberList::insertNode(double num) { ListNode *newnode; // ptr to new node ListNode *nodeptr; // ptr to traverse list ListNode *previousnode; // node previous to nodeptr //allocate new node newnode = new ListNode; newnode->value = num; // empty list, insert at front if (!head) { head = newnode; newnode->next = NULL; else { // initialize the two traversal ptrs nodeptr = head; previousnode = NULL; // skip all nodes less than num while (nodeptr && nodeptr->value < num) { previousnode = nodeptr; // save nodeptr = nodeptr->next; // advance if (previousnode == NULL) { //insert before first head = newnode; newnode->next = nodeptr; else { //insert after previousnode previousnode->next = newnode; newnode->next = nodeptr; Fall 2018 Husain Gholoom Lecturer in Computer Science Page 33

Driver to demo NumberList ListDriver.cpp int main() { // set up the list NumberList list; list.appendnode(2.5); list.appendnode(7.9); list.appendnode(12.6); list.insertnode(10.5); list.displaylist(); return 0; Output: 2.5 7.9 10.5 12.6 Fall 2018 Husain Gholoom Lecturer in Computer Science Page 34

Advantages of linked lists (over arrays) A linked list can easily grow or shrink in size. - The programmer doesn t need to predict how many values could be in the list. - The programmer doesn t need to resize (copy) the list when it reaches a certain capacity. When a value is inserted into or deleted from a linked list, none of the other nodes have to be moved. Advantages of arrays (over linked lists) Arrays allow random access to elements: array[i] - linked lists allow only sequential access to elements (must traverse list to get to i th element). Arrays do not require extra storage for links Fall 2018 Husain Gholoom Lecturer in Computer Science Page 35

Linked List variations Circular linked list - A list in which each node has a successor; the last element is succeeded by the first element Fall 2018 Husain Gholoom Lecturer in Computer Science Page 36

Doubly linked list - Each node has two pointers, o one to the next node and o one to the previous node - Head points to first element, tail points to last. - Can traverse list in reverse direction by starting at the tail and using p=p->prev. Fall 2018 Husain Gholoom Lecturer in Computer Science Page 37

Insertion We visualize operation insertafter(p, X), which returns position q Fall 2018 Husain Gholoom Lecturer in Computer Science Page 38

Deletion We visualize remove(p), where p == last() You tube video to explain the basic concepts of link list : https://www.youtube.com/watch?v=t5nszbieryc&feature=youtu.be Fall 2018 Husain Gholoom Lecturer in Computer Science Page 39

Linked List in C++Standard Template Library ( STL ) Forward list in STL implements singly linked list. Introduced from C++11, forward list are useful than other containers in insertion, removal and moving operations (like sort) and allows time constant insertion and removal of elements. It differs from list by the fact that forward list keeps track of location of only next element while list keeps track to both next and previous elements, thus increasing the storage space required to store each element. The drawback of forward list is that it cannot be iterated backwards and its individual elements cannot be accessed directly. Forward List is preferred over list when only forward traversal is required (same as singly linked list is preferred over doubly linked list) as we can save space. Some example cases are, chaining in hashing, adjacency list representation of graph, etc. Few Operations on Forward List : 1. assign() :- This function is used to assign values to forward list, its another variant is used to assign repeated elements. // Declaring forward list forward_list<int> flist1; // Assigning values using assign() flist1.assign({1, 2, 3); 2. push_front() :- This function is used to insert the element at the first position on forward list. The size of forward list increases by 1. 3. pop_front() :- This function is used to delete the first element of list. // Initializing forward list forward_list<int> flist = {10, 20, 30, 40, 50; // Inserts 60 at front flist.push_front(60); // Deleting first value using pop_front() // Pops 60 flist.pop_front(); Fall 2018 Husain Gholoom Lecturer in Computer Science Page 40

4. insert_after() This function gives us a choice to insert elements at any position in forward list. The arguments in this function are copied at the desired position. // Initializing forward list forward_list<int> flist = {10, 20, 30 ; // Declaring a forward list iterator forward_list<int>::iterator ptr; // Inserting value using insert_after() // starts insertion from second position ptr = flist.insert_after(flist.begin(), {1, 2, 3); 5. erase_after() This function is used to erase elements from a particular position in the forward list. 6. remove() :- This function removes the particular element from the forward list mentioned in its argument. 7. remove_if() :- This function removes according to the condition in its argument. // Initializing forward list forward_list<int> flist = {10, 20, 30, 25, 40, 40; // Removing element using remove() // Removes all occurrences of 40 flist.remove(40); // Displaying the forward list cout << "The forward list after remove operation : "; for (int&c : flist) cout << c << " "; // output 10, 20, 30, 25 cout << endl; // Removing according to condition. Removes // elements greater than 20. Removes 25 and 30 flist.remove_if([](int x){ return x>20;); // output 10, 20 Fall 2018 Husain Gholoom Lecturer in Computer Science Page 41

9. splice_after() :- This function transfers elements from one forward list to other. // Initializing forward list forward_list<int> flist1 = {10, 20, 30; // Initializing second list forward_list<int> flist2 = {40, 50, 60; // Shifting elements from first to second // forward list after 1st position flist2.splice_after(flist2.begin(),flist1); // output is 40 10 20 30 50 60 Fall 2018 Husain Gholoom Lecturer in Computer Science Page 42

List in C++ Standard Template Library (STL) List Lists are sequence containers that allow non-contiguous memory allocation. As compared to vector, list has slow traversal, but once a position has been found, insertion and deletion are quick. Normally, when we say a List, we talk about doubly linked list. For implementing a singly linked list, we use forward list. Functions used with List : front() Returns reference to the first element in the list back() Returns reference to the last element in the list push_front(g) Adds a new element g at the beginning of the list push_back(g) Adds a new element g at the end of the list pop_front() Removes the first element of the list, and reduces size of the list by 1 pop_back() Removes the last element of the list, and reduces size of the list by 1 begin() Returns an iterator pointing to the first element of the list end() Returns an iterator pointing to the theoretical last element which follows the last elementempty() Returns whether the list is empty(1) or not(0) insert() Inserts new elements in the list before the element at a specified position erase() Removes a single element or a range of elements from the list assign() Assigns new elements to list by replacing current elements and resizes the list remove() Removes all the elements from the list, which are equal to given element reverse() Reverses the list size() Returns the number of elements in the list sort() Sorts the list in increasing order Fall 2018 Husain Gholoom Lecturer in Computer Science Page 43

Example #include <iostream> #include <list> #include <iterator> using namespace std; //function for printing the elements in a list void showlist(list<int> g) { list<int>::iterator it; for (it = g.begin(); it!= g.end(); ++it) cout << '\t' << *it; cout << '\n'; int main() { list<int> gqlist1, gqlist2; for (int i = 0; i < 10; ++i) { gqlist1.push_back(i * 2); gqlist2.push_front(i * 3); cout << "\nlist 1 (gqlist1) is : "; showlist(gqlist1); cout << "\nlist 2 (gqlist2) is : "; showlist(gqlist2); cout << "\ngqlist1.front() : " << gqlist1.front(); cout << "\ngqlist1.back() : " << gqlist1.back(); cout << "\ngqlist1.pop_front() : "; gqlist1.pop_front(); showlist(gqlist1); cout << "\ngqlist2.pop_back() : "; gqlist2.pop_back(); showlist(gqlist2); cout << "\ngqlist1.reverse() : "; gqlist1.reverse(); showlist(gqlist1); cout << "\ngqlist2.sort(): "; gqlist2.sort(); showlist(gqlist2); return 0; Fall 2018 Husain Gholoom Lecturer in Computer Science Page 44

The output of the above program is : List 1 (gqlist1) is : 0 2 4 6 8 10 12 14 16 18 List 2 (gqlist2) is : 27 24 21 18 15 12 9 6 3 0 gqlist1.front() : 0 gqlist1.back() : 18 gqlist1.pop_front() : 2 4 6 8 10 12 14 16 18 gqlist2.pop_back() : 27 24 21 18 15 12 9 6 3 gqlist1.reverse() : 18 16 14 12 10 8 6 4 2 gqlist2.sort(): 3 6 9 12 15 18 21 24 27 Fall 2018 Husain Gholoom Lecturer in Computer Science Page 45