Building a Linked List in Java. Linked List In the Procedural Paradigm a linked list consisted of: –A pointer to the head of the list –Nodes (in dynamic.

Slides:



Advertisements
Similar presentations
1 Linked Lists Continued Lecture 5 Copying and sorting singly linked lists Lists with head and last nodes Doubly linked lists ADS2 Lecture 5.
Advertisements

Singly linked lists Doubly linked lists
1 - Recursion on linked lists Lecture 7 ADS2 Lecture 7.
Linked List: Traversal Insertion Deletion. Linked List Traversal LB.
Linked Lists Chapter 4.
1/27 COP 3540 Data Structures with OOP Chapter 5 Linked Lists.
Linked List 1. Introduction to Linked List 2. Node Class 3. Linked List 4. The Bag Class with Linked List.
Linked lists CSCI 2170.
Data Structure Lecture-3 Prepared by: Shipra Shukla Assistant Professor Kaziranga University.
Based on Java Software Development, 5th Ed. By Lewis &Loftus
Simple Programs Simple Strings Writing some programs Only in Parameters? I/O Gadget.
The Point Class public class Point { public double x; public double y; public Point(double x0, double y0) { x = x0; y = y0; } public double distance(Point.
Linked Lists. 2 Merge Sorted Lists Write an algorithm that merges two sorted linked lists The function should return a pointer to a single combined list.
Ics202 Data Structures. hh tail head (b) LinkedList head tail Element datum next 3 Integer Element datum next 1 Integer Element datum next 4 Integer.
The Singleton Pattern II Recursive Linked Structures.
Topic 10 Java Memory Management. 1-2 Memory Allocation in Java When a program is being executed, separate areas of memory are allocated for each class.
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
Data Structures: A Pseudocode Approach with C 1 Chapter 5 Contd... Objectives Explain the design, use, and operation of a linear list Implement a linear.
Linked Lists. Preliminaries Options for implementing an ADT List Array Has a fixed size Data must be shifted during insertions and deletions Dynamic array.
Object Oriented Programming.  OOP Basic Principles  C++ Classes  September 2004  John Edgar 22.
1 More on Classes Overview l Overloading l The this keyword l The toString method l The equals method.
13 X 11 Java Lecture 6 CS 1311X Self-Referential Structures Building a Queue 13 X 11.
CMSC 202 Lesson 23 Templates II. Warmup Write the templated Swap function _______________________________ void Swap( ________ a, ________ b ) { _______________.
CSE 131 Computer Science 1 Module 9: Linked Lists Using references to link objects Basic operations on linked lists Implementing a linked list of integers.
Parameters. Overview A Reminder Why Parameters are Needed How Parameters Work Value Parameters Reference Parameters Out Parameters.
Lecture # 8 Constructors Overloading. Topics We will discuss the following main topics: – Static Class Members – Overloaded Methods – Overloaded Constructors.
Classes and Objects Class: describes the form of an object, a template or blueprint or mold specifies data representation, behavior, and inheritance.
ليست هاي پيوندي Linked Lists ساختمان داده ها و الگوريتم ها.
1 Writing a Good Program 8. Elementary Data Structure.
Linked Lists Ellen Walker CPSC 201 Data Structures Hiram College.
JAVA Classes Review. Definitions Class – a description of the attributes and behavior of a set of computational objects Constructor – a method that is.
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
4-1 Topic 6 Linked Data Structures. 4-2 Objectives Describe linked structures Compare linked structures to array- based structures Explore the techniques.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 17: Linked Lists.
Introduction to Classes and Objects. Real Life When a design engineer needs an electrical motor he doesn’t need to worry about –How a foundry will cast.
Classes. Student class We are tasked with creating a class for objects that store data about students. We first want to consider what is needed for the.
Introduction to Data Structures and Algorithms
Static?. Static Not dynamic class Widget { static int s; int d; // dynamic // or instance // variable }
CS 367 Introduction to Data Structures Lecture 5.
1 Java linked list. Java linked list - definition ▪ Often in programming we are required to systematically store some type of information. A prime example.
Bank Account Example public class BankAccount { private double balance; public static int totalAccounts = 0; public BankAccount() { balance = 0; totalAccounts++;
Chapter 5 Linked List by Before you learn Linked List 3 rd level of Data Structures Intermediate Level of Understanding for C++ Please.
Arrays and ArrayLists Topic 6. One Dimensional Arrays Homogeneous – all of the same type Contiguous – all elements are stored sequentially in memory For.
Engineering Classes. Objectives At the conclusion of this lesson, students should be able to: Explain why it is important to correctly manage dynamically.
Java linked list.
The Vector Class. Vector Class Write a Vector class. This will be a container class that will hold objects. It should allow the following operations:
Data Structures AZHAR MAQSOOD NUST Institute of Information Technology (NIIT) Lecture 6: Linked Lists Linked List Basics.
Linked Lists CS 367 – Introduction to Data Structures.
Linked Lists A formal data structure. Linked Lists Collections of data items “lined up in a row” Inserts and deletes can be done anywhere in the list.
Data Abstraction and Problem Solving with JAVA Walls and Mirrors Frank M. Carrano and Janet J. Prichard © 2001 Addison Wesley Data Abstraction and Problem.
Linked Data Structures
Memory Management.
Java Memory Management
COMP 53 – Week Eight Linked Lists.
Sequences 5/10/2018 2:01 PM Linked Lists Linked Lists.
Copy Constructor / Destructors Stacks and Queues
Java Memory Management
CS2006- Data Structures I Chapter 5 Linked Lists I.
Exercise 1 From Lec80b-Ponter.ppt.
Simple Dynamic Data (Linked Lists)
Stack Lesson xx   This module shows you the basic elements of a type of linked list called a stack.
Prof. Neary Adapted from slides by Dr. Katherine Gibson
Chapter 16-2 Linked Structures
Lecture 11 C Parameters Richard Gesick.
Initializing Objects.
Linked Lists [AJ 15].
More on Classes and Objects
Introduction to Algorithms and Data Structures
Linked List Functions.
Presentation transcript:

Building a Linked List in Java

Linked List In the Procedural Paradigm a linked list consisted of: –A pointer to the head of the list –Nodes (in dynamic memory i.e. the heap) containing data and additional next pointers –Modules that would perform a variety of functions as needed: add (in order), traverse, find, delete, etc. In the Object Oriented Paradigm a linked list will consist of a class which contains: –The head pointer (globally scoped in the class) –Methods to perform the function listed above We will also need a class to hold the nodes. We’ll start with that...

Node class Node { StudentRecord data; Node next; public Node(StudentRecord data) { setData(data); setNext(null); } // Constructor public void setData(StudentRecord data) { this.data = data; // !!!!!!!!!!!!!!!!!!!!!!!!!! } public void setNext(Node next) { this.next = next; } public StudentRecord getData() { return data; } public Node getNext() { return next; } public String toString() { if(data == null) return "Node: null"; else return "Node: " + data.toString(); } Comments omitted for clarity!!! Comments omitted for clarity!!!

Are we done? What about the test main???

Remember the main(e) public static void main(String args[]) { StudentRecord sr = new StudentRecord("Bob", 3.5, ); Node n1 = new Node(null); System.out.println("Empty node test\n" + n1); // Load up and print n1.setData(sr); System.out.println("Bob: "+n1); sr = new StudentRecord("Mary", 3.7, ); Node n2 = new Node(sr); n1.setNext(n2); System.out.println("Bob: "+n1); System.out.println("Mary: "+n2); } // main } // Node

Let’s see what’s happening

Tracing StudentRecord sr = new StudentRecord("Bob", 3.5, ); name = "Bob" gpa = 3.5 ssn = sr

Tracing Node n1 = new Node(null); name = "Bob" gpa = 3.5 ssn = sr n1 data next

Tracing n1.setData(sr); name = "Bob" gpa = 3.5 ssn = sr n1 data next

Tracing sr = new StudentRecord("Mary", 3.7, ); name = "Bob" gpa = 3.5 ssn = sr n1 data next name = "Mary" gpa = 3.7 ssn =

Tracing Node n2 = new Node(sr); name = "Bob" gpa = 3.5 ssn = sr n1 data next name = "Mary" gpa = 3.7 ssn = n2 data next

Tracing n1.setNext(n2); name = "Bob" gpa = 3.5 ssn = sr n1 data next name = "Mary" gpa = 3.7 ssn = n2 data next

Key to Understanding Java Understand that the "variables" that you may think of as objects (not primitives) are ALWAYS references (like pointers) to objects which live in the heap. The objects live and die immobile in the heap All the apparent movement of objects is just the moving, copying, setting-to-null of references

Review We have created and tested two classes –class StudentRecord –class Node We now construct the class LinkedList We’ll start with the fields and simple accessors/modifiers Then we’ll write the add, traverse, find and delete methods (plus helpers if necessary)

LinkedList class LinkedList { private Node head; public LinkedList() { setHead(null); } // constructor private void setHead(Node head) { this.head = head; } // setHead private Node getHead() { return head; } // getHead

LinkedList (add method) // Purpose: add in order by SSN // Postcon: list will contain one additional item public void add(StudentRecord sr) { if(getHead() == null || getHead().getData().getSsn() > sr.getSsn() ) { Node temp = new Node(sr); temp.setNext(getHead()); setHead(temp); } else { add(getHead(), sr); } } // add

LinkedList (add helper method) // Purpose: add helper private void add(Node cur, StudentRecord sr) { if( cur.getNext() == null || cur.getNext().getData().getSsn() > sr.getSsn() ) { Node temp = new Node(sr); temp.setNext(cur.getNext()); cur.setNext(temp); } else { add(cur.getNext(), sr); } } // add

LinkedList (traverse ) // Purpose: traverse list // Postcon: no change to list public void traverse() { traverse(getHead()); } // traverse // Purpose: traverse helper private void traverse(Node cur) { if(cur != null) { System.out.println(cur); traverse(cur.getNext()); } } // traverse

LinkedList (traverse ) // Purpose: print out string passed in as parameter // then traverse list (useful for // debugging) // Postcon: No change to list public void traverse(String s) { System.out.println(s); traverse(); } // traverse

LinkedList (traverse iteratively ) // Purpose: traverse iteratively (just shown for // comparison // Postcon: No change to list public void traverseI() { Node cur = getHead(); while(cur != null) { System.out.println(cur); cur = cur.getNext(); } } // traverseI // Purpose: traverse iteratively with title public void traverseI(String s) { System.out.println(s); traverseI(); } // traverseI

LinkedList (find ) // Purpose: Locate record by SSN // Postcon: No change to list public StudentRecord find(int targSsn) { return find(getHead(), targSsn); } // find // Purpose: Find helper private StudentRecord find(Node cur, int targSsn) { if(cur == null) return null; else if(cur.getData().getSsn() == targSsn) { return cur.getData(); } else { return find(cur.getNext(), targSsn); } } // find

LinkedList (deleteFirst) occurence // Purpose: delete first occurence of record with // matching SSN // Postcon: If SSN found record will be removed thus // list will be one shorter public void deleteFirst(int targSsn) { if(getHead() != null) { if(getHead().getData().getSsn() == targSsn) { setHead(getHead().getNext()); } else { deleteFirst(getHead(), targSsn); } } // deleteFirst

LinkedList (deleteFirst) occurence // Purpose: delete first occurence helper private void deleteFirst(Node cur, int targSsn) { if(cur.getNext() != null) { if(cur.getNext().getData().getSsn() == targSsn) { cur.setNext(cur.getNext().getNext()); } else { deleteFirst(cur.getNext(), targSsn); } } // deleteFirst

LinkedList (deleteAll) occurences // Purpose: delete all occurences matching a target // SSN // Postcon: All matching occurences will be // eliminated public void deleteAll(int targSsn) { // (Extra Credit!!!) }

LinkedList (main) public static void main(String args[]) { LinkedList ell = new LinkedList(); ell.traverse("Empty list traversal"); ell.add(new StudentRecord("Adam", 3.0, 333)); ell.add(new StudentRecord("Bozo", 2.0, 222)); ell.add(new StudentRecord("Carl", 1.0, 444)); ell.traverseI("Should be "); ell.add(new StudentRecord("Doug", 0.0, 111)); ell.traverse("Should be "); ell.deleteFirst(222); ell.traverseI("Should be "); ell.deleteFirst(999); ell.deleteFirst(333); ell.deleteFirst(111); ell.deleteFirst(444); ell.traverse("Empty list???"); } // main } // LinkedList

Application /* Demo application to allow user to add, find, list, * and delete student records */ class Application { // Purpose: print menu and get user choice // Postcon: returns choice as int public static int menuChoice() { System.out.println("Enter 1 to add"); System.out.println("Enter 2 to find"); System.out.println("Enter 3 to list"); System.out.println("Enter 4 to delete"); System.out.println("Enter 5 to quit"); return IOGadget.readInt("Choice"); }

Application // Purpose: get information to fill student record // Postcon: returns filled StudentRecord public static StudentRecord getSR() { String name = IOGadget.readLine("Name"); double gpa = IOGadget.readDouble("GPA"); int ssn = IOGadget.readInt("SSN"); return new StudentRecord(name, gpa, ssn); }

Application // print menu and fulfill request public static void menuloop() { LinkedList list = new LinkedList(); int choice; do { choice = menuChoice(); if(choice == 1) list.add(getSR()); else if(choice == 2) { StudentRecord sr = list.find(IOGadget.readInt("SSN")); if(sr == null) System.out.println("Not found"); else System.out.println(sr); }

Application else if(choice == 3) list.traverse("Student List"); else if(choice == 4) { int ssn = IOGadget.readInt("SSN?"); list.deleteFirst(ssn); } else if(choice == 5) System.out.println("Exiting"); else System.out.println("Illegal choice"); } while(choice != 5); } // menuloop

Application public static void main(String args[]) { menuloop(); } } // class Application

Diagram class Application menuloop { LinkedList list } main { menuloop() } class LinkedList LLNode head methods… LinkedList object head class LLNode StuRec data LLNode next methods… LLNode object StuRec data LLNode next LLNode object StuRec data LLNode next Instance of