James Tam Linked Lists In this section of notes you will learn how to create and manage a dynamic list.

Slides:



Advertisements
Similar presentations
Chapter 17 Linked Lists.
Advertisements

Stacks, Queues, and Linked Lists
James Tam Linked Lists in Pascal Linked Lists In this section of notes you will learn how to create and manage a dynamic list.
DATA STRUCTURES USING C++ Chapter 5
Module R2 CS450. Next Week R1 is due next Friday ▫Bring manuals in a binder - make sure to have a cover page with group number, module, and date. You.
Linked Lists Compiled by Dr. Mohammad Alhawarat CHAPTER 04.
Linked Lists
J. Michael Moore Text Files CSCE 110 From James Tam’s material.
James Tam Records You will learn in this section of notes how to create a new, composite type, that can be composed of different types of elements.
James TamThe Bubble Sort in Pascal Sorting (Bubble) In this section of notes you will learn one technique for ordering a list.
James Tam Sorting (Bubble) In this section of notes you will learn one technique for ordering a list.
James Tam Sorting (Bubble) In this section of notes you will learn one technique for ordering a list.
James Tam Introduction To Files In Pascal In this section of notes you will learn how to read from and write to files in Pascal.
James Tam Sorting (Bubble) In this section of notes you will learn one technique for ordering a list.
James Tam Data structures in Java Data Structures In Java In this section of notes you will learn about two common types of data structures: Queues Stacks.
James Tam Introduction To Files In Pascal In this section of notes you will learn how to read from and write to files in your Pascal programs.
James Tam Records You will learn in this section of notes how to create a new, composite type, that can be composed of different types of elements.
James Tam Linked Lists In this section of notes you will learn how to create and manage a dynamic list.
James Tam Sorting (Bubble) In this section of notes you will learn one technique for ordering a list.
James Tam Records You will learn in this section of notes how to create a new, composite type, that can be composed of different types of elements.
James Tam program investors (input, output, investorList, updatedInvestorList); const MAXCLIENTS = 10; NAMELENGTH = 30; LENGTH = 30; type Client =
James Tam Records You will learn in this section of notes how to create a new, composite type, that can be composed of different types of elements.
Lists Lists as an abstract data type (ADT)
James Tam Linked Lists In this section of notes you will learn how to create and manage a dynamic list.
J. Michael Moore From James Tam's material Records CSCE 110.
James Tam Records You will learn in this section of notes how to create a new, composite type, that can be composed of different types of elements.
James Tam Linked Lists In this section of notes you will learn how to create and manage a dynamic list.
Link Lists In this section of notes you will learn how to create and manage a dynamic list. Link Lists in Pascal.
James Tam Records You will learn in this section of notes what is a record and how to use them in Pascal.
James Tam Pointers In this section of notes you will learn about another type of variable that stores addresses rather than data.
C++ Programming: Program Design Including Data Structures, Fifth Edition Chapter 17: Linked Lists.
Chapter 12 Pointers and linked structures. 2 Introduction  The data structures that expand or contract as required during the program execution is called.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
1 CSC 222: Computer Programming II Spring 2004 Pointers and linked lists  human chain analogy  linked lists: adding/deleting/traversing nodes  Node.
Searching: Binary Trees and Hash Tables CHAPTER 12 6/4/15 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,
Chapter 1 Object Oriented Programming. OOP revolves around the concept of an objects. Objects are created using the class definition. Programming techniques.
CSC 211 Data Structures Lecture 13
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.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
Copyright © 2012 Pearson Education, Inc. Chapter 17: Linked Lists.
Pascal Programming Pointers and Dynamic Variables.
Pascal Programming Today Chapter 11 1 Chapter 11.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
Chapter 5 Linked List by Before you learn Linked List 3 rd level of Data Structures Intermediate Level of Understanding for C++ Please.
COP 3540 Data Structures with OOP
Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan.
Chapter 17: Linked Lists. Objectives In this chapter, you will: – Learn about linked lists – Learn the basic properties of linked lists – Explore insertion.
1 CSC 211 Data Structures Lecture 11 Dr. Iftikhar Azim Niaz 1.
1 Linked List. Outline Introduction Insertion Description Deletion Description Basic Node Implementation Conclusion.
Single Linked Lists Objectives In this lesson, you will learn to: *Define single linked list *Identify the following types of linked lists: Single linked.
Linked Lists Chapter Introduction To The Linked List ADT Linked list: set of data structures (nodes) that contain references to other data structures.
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.
CHAPTER 51 LINKED LISTS. Introduction link list is a linear array collection of data elements called nodes, where the linear order is given by means of.
Arrays, Link Lists, and Recursion Chapter 3. Sorting Arrays: Insertion Sort Insertion Sort: Insertion sort is an elementary sorting algorithm that sorts.
LINKED LISTS.
Copyright © 2012 Pearson Education, Inc. Chapter 17: Linked Lists.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Chapter 16: Linked Lists.
C++ Programming:. Program Design Including
Data Structures Using C, 2e
Linked List :: Basic Concepts
Lecture - 6 On Data Structures
UNIT-3 LINKED LIST.
Data Structures Interview / VIVA Questions and Answers
Prof. Neary Adapted from slides by Dr. Katherine Gibson
Linked Lists Chapter 10.
Chapter 18: Linked Lists.
Sorting (Bubble) In this section of notes you will learn one technique for ordering a list.
Presentation transcript:

James Tam Linked Lists In this section of notes you will learn how to create and manage a dynamic list.

James Tam Arrays Easy to use but suffer from a number of drawbacks: 1) Fixed size 2) Adding/Deleting elements can be awkward

James Tam Arrays: Fixed Size The size of the array cannot be dynamically changed once the memory has been allocated The following example won't work: program notAllowed (input, output); var size : integer; arr : array [1..size] of integer; begin write('Enter size of array: '); readln(size); end. The workaround is to allocate more space than you need

James Tam Arrays: Fixed Size The size of the array cannot be dynamically changed once the memory has been allocated The following example won't work: program notAllowed (input, output); var size : integer; arr : array [1..size] of integer; begin write('Enter size of array: '); readln(size); end. The workaround is to allocate more space than you need The size of the array must be predetermined!

James Tam Arrays: Adding Elements In The Middle

James Tam Arrays: Deleting Elements From The Middle

James Tam What’s Needed A composite type that stores data dynamically and can allow for the quick addition and removal of elements Freight “data” Connector

James Tam Alternative To Arrays: Linked Lists More complex coding may be required Some list management functions are more elegant (and faster) DataPtr Node DataPtrDataPtr Linked List Head

James Tam Common List Functions 1) Declaring the list 2) Creating a new list 3) Traversing the list 4) Adding a node to the list 5) Searching the list 6) Deleting a node from the list Note: These list functions will be illustrated by portions of an example that is a modified version of the investors program from the section on sorting, but implemented as a linked list rather than as array. The complete program can be found in Unix under: /home/231/examples/linkedLists/investors.p

James Tam Declaring A Linked List Format: (* Part I: Defining a new type for the data (necessary if the data field is not a built-in type *) (* Part II: Defining a pointer to the new type “Node” *) Name of the list pointer = ^ Node; (* Part III: Defining a new type, a “Node” *) type Node = record data : Name of the list data; nextPointer : Name of the list pointer; end; Part I: What is the data? Part II: What is the connector linking? Part III: What is does the entire freight car consist of? (Data and link)

James Tam Declaring A Linked List (2) Example: type (* Part I: Defining a new type for the data (necessary because a “Client” is not a built-in type *) Client = record firstName : string [NAME_LENGTH]; lastName : string [NAME_LENGTH]; income : real; string [ _LENGTH]; end; (* Declaration of record Client *) (* Part II: Defining a pointer to the new type “Node” *) NodePointer = ^ Node;

James Tam Declaring A Linked List (3) (* Part III: Defining a new type, a “Node” *) Node = record data : Client; nextPointer : NodePointer; end; (* Declaration of record Node *)

James Tam Outline Of The Example Program addToList display List addmodifyerasesearch Main loop Blue = Linked list functions addToList main display Instructions createNew List readClient Information display Menu saveClient Information handle Menu- Selection

James Tam Main Procedure: Example Program begin var tamjClientList: NodePointer; var menuSelection: char; var updatedInvestorData: text; displayInstructions; createNewList(tamjClientList); readClientInformation(tamjClientList); repeat begin displayMenu; readln(menuSelection); writeln; processMenuSelection(tamjClientList,menuSelection); end; (* repeat-until *) until (menuSelection = 'Q') OR (menuSelection = 'q'); saveClientInformation(tamjClientList); end.

James Tam Creating A New List Description: The pointer to the beginning of the list is passed into the procedure as a variable parameter and initialized to NIL signifying that the new list is empty. Example: procedure createNewList (var aClientList : NodePointer); begin aclientList := NIL; end; (* createNewList *)

James Tam Reading The Client Information From A File procedure readClientInformation (var aClientList : NodePointer); var newNode : NodePointer; newClient : Client; investorData : text; inputFileName : string [MAX_FILE_NAME_LENGTH]; begin; writeln; write('Enter the name of the input file: '); readln(inputFileName); reset(investorData, inputFileName); writeln('Opening file ', inputFileName, ' for reading'); if EOF (investorData) then begin writeln('File ', inputFileName, ' is empty, nothing to read.'); end

James Tam Reading The Client Information From A File (2) else begin while NOT EOF (investorData) do begin new(newNode); with newClient do begin readln(investorData, firstName); readln(investorData, lastName); readln(investorData, income); readln(investorData, ); readln(investorData); end; newNode^.data := newClient; addToList (aClientList, newNode); end;

James Tam Reading The Client Information From A File (3) newNode^.data := newClient; addToList (aClientList, newNode); end; (* while *) end; (* else *) close(investorData); end; (* readClientInformation *)

James Tam Handling/Executing The Main Menu Of Operations procedure processMenuSelection (var aClientList : NodePointer; menuSelection : char); var desiredName : string[NAME_LENGTH]; isFound : boolean; previousFirst : NodePointer; begin case (menuSelection) of 'D', 'd' : begin displayList (aClientList); end; 'A', 'a' : begin addClient (aClientList); end;

James Tam Handling/Executing The Main Menu Of Operations (2) 'E', 'e' : begin erase (aClientList); end; 'M', 'm' : begin modify (aClientList); end; 'S', 's' : begin write('Enter last name of contact that you wish to search for: '); readln(desiredName); search (aClientList, desiredName, isFound, previousFirst); end;

James Tam Handling/Executing The Main Menu Of Operations (3) 'Q', 'q' : begin writeln; writeln('Thank you for using the investor 2000 (TM) program.'); writeln('Come again!'); writeln; end; else begin writeln; writeln('Please enter one of the following options: d, a, e, m, s or q'); writeln; end; end; (* case *) end; (* End of procedure processMenuSelection *)

James Tam Traversing The List (Display List) Description: Steps (traversing the list to display the data of each node onscreen) 1. Start by initializing a pointer to point to the beginning of the list. 2. If the pointer is NIL then display a message onscreen indicating that there are no nodes to display and stop otherwise proceed to next step. 3. Process the node (e.g., display the data onscreen) 4. Move on to the next node by following the node's nextPointer (set the pointer to point to the next node). 5. Check if the pointer is NIL. a)If the pointer is NIL then stop b)If the pointer is not NIL then go to step #3.

James Tam Traversing The List (2) Example: procedure displayList (aClientList : NodePointer); var i : integer; begin writeln('CLIENT LIST':19); for i := 1 to 20 do write('--'); writeln; if (aClientList = NIL) then begin writeln; writeln('List is empty, no clients to display'); writeln; end;

James Tam Traversing The List (3) while (aClientList <> NIL) do begin writeln('First name: ':20, aClientList^.data.firstName); writeln('Last Name: ':20, aClientList^.data.lastName); writeln('Income $':20, aClientList^.data.income:0:2); writeln(' ':20, aClientList^.data. ); writeln; aClientList := aClientList^.nextPointer; end; end; (* displayList *)

James Tam Traversing The List (4)

James Tam Traversing The List (5)

James Tam Adding A Node To The End Of The List Description: Variables 1. There are two pointers to the list: a) Current pointer – traverses the list from beginning to end b) Previous to first pointer – points to the node that occurs just prior to the first successful match.

James Tam Adding A Node To The End Of The List (2) Steps: 1. Assign current pointer to the front of the list. 2. If the current pointer is NIL then the list is empty and add the node to the front of the list and stop. 3. Otherwise traverse the list with two pointers, one pointer (current pointer) goes past the end of the list (to the NIL value), the other stays one node behind it (previous pointer). 4. Attach the new node to the last node in the list (the one reached by the previous pointer). 5. The next pointer of the new node becomes NIL (indicating that this is the end of the list).

James Tam Adding A Node To The End Of The List (3) Example: procedure addToList (var aClientList : NodePointer; newNode : NodePointer); var currentNode: NodePointer; previousNode: NodePointer; begin if (aClientList = NIL) then begin aClientList := newNode; newNode^.nextPointer := NIL; end

James Tam Adding A Node To The End Of The List (4) begin currentNode := aClientList; while (currentNode <> NIL) do begin previousNode := currentNode; currentNode := currentNode^.nextPointer; end; previousNode^.nextPointer := newNode; newNode^.nextPointer := NIL; end; end; (* addToList *)

James Tam Adding A Node To The End Of The List (5)

James Tam Adding A Node To The End Of The List (6)

James Tam Searching The List Description: The procedure is run in order to find a node or nodes that has a field which matches some desired value. Either the node or nodes will be found in the list or else the procedure will have searched every node in the list and have found no matches. A flag will be set to true or false indicating whether the search was successful or a failure. Main variables: 1. There are two pointers to the list: a. Current pointer – traverses the list from beginning to end. b. Previous to first pointer – points to the node that occurs just prior to the first successful match. Note: The second pointer is not used when the user only wants to search the list. It is needed when the person wishes to erase a node from the list. Since the erase procedure calls the search procedure, it needs a pointer to the node prior to the one to be deleted. 2. A Boolean that indicates the status of the search.

James Tam Searching The List (2) Steps: 1.Current pointer starts at the beginning of the list. Since the search has not yet begin, previous is set to NIL and the flag is set to false. 2.A check is performed to determine if the node is a match. If this is the case and the flag is still false (indicating that we haven't found a previous node that was a successful match) set the flag to true (since a match was just found). Since the search function requires a list of all matches (and not just the first instance) don't stop searching the list. 3.The previous pointer to will be set to point to the current node if the flag was false prior to the match (i.e., this is the first instance found). The previous pointer will not change if the flag was already set to true (the previous pointer will still track the node just prior to the node which first meets the search criteria). 4.Move on to the next node (by setting the current pointer to the current node's next pointer). 5.Continue step 2 – 4 until the end of the list is reached (current node is NIL).

James Tam Searching The List (3) Example: procedure search ( aClientList: NodePointer; desiredName: string; var isFound: boolean; var previousFirst: NodePointer ); var currentNode : NodePointer; begin currentNode := aClientList; previousFirst := NIL; isFound := False;

James Tam Searching The List (4) while (currentNode <> NIL) do begin if (desiredName = currentNode^.data.lastName) then begin writeln('Found contact':20); writeln('First name :':20, currentNode^.data.firstName); writeln('Last name :':20, currentNode^.data.lastName); writeln('Income $':20, currentNode^.data.income:0:2); writeln(' ':20, currentNode^.data. ); writeln; if (isFound = False) then isFound := True; end; (* if-then *) if (isFound = False) then previousFirst := currentNode; currentNode := currentNode^.nextPointer; end; (* while *) if (isFound = False) then writeln('Contact not found in list'); end; (* search *)

James Tam Searching The List (5)

James Tam Searching The List (6)

James Tam Searching The List (7)

James Tam Deleting (Erasing) A Node From The List Description: Main variables: 1. A flag that indicates the status of the search. If the search was successful then it was true that the item was found (flag will be set to true). If the search was a failure then it was false that item was found (flag will be set to false). 2. A pointer that points to the node just prior to the one to be deleted. If the flag was set to true then the pointer contains the address of the previous node. If the pointer is NIL then the node to be deleted is the first node (nothing is previous to this node so there is no address). If the the pointer is not NIL then it contains the address of the node to be deleted. 3. A temporary pointer that points to the node to be deleted. It is needed so that the program can retain a reference to this node and free up the memory allocated for it.

James Tam Deleting (Erasing) A Node From The List (2) Steps 1.Search the list (by calling the search procedure) to determine if there exists a node that matches the necessary criteria for deletion. 2.Check the flag to determine if the search was successful or not. If the flag is false then there is no matching node in the list. End procedure: There is no matching node to delete. 3.Check to see if the node to be deleted is the first node in the list or not by checking if the previous pointer is NIL. 4.If the node to be deleted is the first node then have a temporary pointer point to the first element and make the front of the list the second element. 5.If the node to be deleted is not the first node then have a temporary pointer point to the node to be deleted. Set the next pointer (of the node previous to the one to be deleted) point to the node after the node to be deleted (bypassing the node to be deleted) 6.For steps 4 & 5 free up the memory allocated by the node to be deleted by dereferencing the temporary pointer.

James Tam Deleting A Node From The List (3) Example: procedure erase (var aClientList : NodePointer); var desiredName : string[NAME_LENGTH]; previousFirst : NodePointer; temp : NodePointer; isFound : boolean; begin write('Enter last name of client to delete: '); readln(desiredName); search (aClientList, desiredName, isFound, previousFirst);

James Tam Deleting A Node From The List (4) if (isFound = True) then begin writeln('Deleting first instance of ', desiredName); if (previousFirst = NIL) then begin temp := aClientList; aClientList := aClientList^.nextPointer; end (* if-then *) else begin temp := previousFirst^.nextPointer; previousFirst^.nextPointer := temp^.nextPointer; end; (* else: not deleting first *) dispose(temp); end; (* if-then: check if client in list *) end; (* else: searching list when list isn't empty *)

James Tam Deleting A Node From The List (5)

James Tam Deleting A Node From The List (6)

James Tam Deleting A Node From The List (7)

James Tam You Should Now Know What is a linked list What are the advantages of using a linked list over using an array What is the disadvantage of using a linked list over using an array Common list operations Declaring a list Creating a new list and initializing the list with data Traversing the list (e.g., to display the contents of the nodes) Adding new nodes to the list Searching the list Deleting an existing node from the list