Linked Lists. private int num; // payload for the node private Node next; // pointer to the next node in the list }

Similar documents
// Pointer to the first thing in the list

CS201 ArrayLists, Generics, and Dynamic Data Structures (Chapters 14, 15)

Introduction to Linked Data Structures

CSC 172 Data Structures and Algorithms. Lecture #9 Spring 2018

Repetition, Looping. While Loop

ADTs, Arrays, Linked Lists

Controls Structure for Repetition

St. Edmund Preparatory High School Brooklyn, NY

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Problem Solving With Loops

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Name Section Number. CS210 Exam #2 *** PLEASE TURN OFF ALL CELL PHONES*** Practice

Static Methods. Why use methods?

CS24 Week 4 Lecture 2

Linked Lists. College of Computing & Information Technology King Abdulaziz University. CPCS-204 Data Structures I

CMPSCI 187: Programming With Data Structures. Lecture #26: Binary Search Trees David Mix Barrington 9 November 2012

Lecture 3. Lecture

Week 11. Abstract Data Types. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Ch. 6. User-Defined Methods

Over and Over Again GEEN163

Linked Lists. Chapter 12.3 in Savitch

Lecture 17. For Array Class Shenanigans

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

COL106: Data Structures and Algorithms. Ragesh Jaiswal, IIT Delhi

Loops. CSE 114, Computer Science 1 Stony Brook University

CSE 1223: Introduction to Computer Programming in Java Chapter 6 ArrayLists

Here is how we use an arraylist. To access the arraylist code we can import the class via:

University of Cape Town ~ Department of Computer Science. Computer Science 1015F ~ 2007

CIS Fall Data Structures Midterm exam 10/16/2012

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

AP Computer Science Unit 1. Programs

Arrays. Chapter 7 (Done right after 4 arrays and loops go together, especially for loops)

It is a constructor and is called using the new statement, for example, MyStuff m = new MyStuff();

Please answer the following questions. Do not re-code the enclosed codes if you have already completed them.

1 Short Answer (10 Points Each)

Example Program. public class ComputeArea {

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Dynamic Data Structures

Fundamentals of Programming Data Types & Methods

CSC 172 Data Structures and Algorithms. Lecture #8 Spring 2018

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR

The NetBeans IDE is a big file --- a minimum of around 30 MB. After you have downloaded the file, simply execute the file to install the software.

Linked Lists. References and objects

First Java Program - Output to the Screen

News and information! Review: Java Programs! Feedback after Lecture 2! Dead-lines for the first two lab assignment have been posted.!

Example: Monte Carlo Simulation 1

Menu Driven Systems. While loops, menus and the switch statement. Mairead Meagher Dr. Siobhán Drohan. Produced by:

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

STUDENT LESSON A12 Iterations

Page 1 / 3. Page 2 / 18. Page 3 / 8. Page 4 / 21. Page 5 / 15. Page 6 / 20. Page 7 / 15. Total / 100. Pledge:

CS24 Week 4 Lecture 1

Arrays. COMS W1007 Introduction to Computer Science. Christopher Conway 10 June 2003

CS32 Discussion Sec.on 1B Week 2. TA: Zhou Ren

King Saud University College of Computer and Information Systems Department of Computer Science CSC 113: Java Programming-II, Spring 2016

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Flow of Control: Loops. Chapter 4

Introduction To Data Structures

Nested Loops. A loop can be nested inside another loop.

Repetition CSC 121 Fall 2014 Howard Rosenthal

Chapter 17: Linked Lists

Loops. GEEN163 Introduction to Computer Programming

1. ArrayList and Iterator in Java

Linked Lists. Chapter 4

For example, when we first started Java programming we described the HelloWorld class:

CMPT 125: Lecture 4 Conditionals and Loops

CSC 1051 Villanova University. CSC 1051 Data Structures and Algorithms I. Course website:

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops

CIS 1068 Program Design and Abstraction Spring2016 Midterm Exam 1. Name SOLUTION

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

Introduction to the Java Basics: Control Flow Statements

DM537 Object-Oriented Programming. Peter Schneider-Kamp.

Cosc 241 Programming and Problem Solving Lecture 9 (26/3/18) Collections and ADTs

Insertions and removals follow the Fist-In First-Out rule: Insertions: at the rear of the queue Removals: at the front of the queue

FORM 2 (Please put your name and form # on the scantron!!!!)

CSC 1051 Data Structures and Algorithms I

Chapter 17: Linked Lists

Warm up Exercise. What are the types and values of the following expressions: * (3 + 1) 3 / / 2.0 (int)1.0 / 2

CSE 20. SAMPLE FINAL Version A Time: 180 minutes. The following precedence table is provided for your use:

COSC 123 Computer Creativity. Java Lists and Arrays. Dr. Ramon Lawrence University of British Columbia Okanagan

Part (II): In the body method main : Write the call to method formatname and have the return value stored in the variable formatted.

Assignment 8B SOLUTIONS

Data Structures (CS301) LAB

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

ECM1406. Answer Sheet Lists

Week 14 Lab A Linked List of Integers Maximum Points = 10

Loops. Repeat after me

2/22/2013 LISTS & TREES

Darrell Bethea May 10, MTWRF 9:45-11:15 AM Sitterson 011

16. Dynamic Data Structures

Programming II (CS300)

ITI Introduction to Computing II

CMSC 341 Lecture 7 Lists

Spring 2016 Programming Languages Qualifying Exam

Faculty of Science COMP-202B - Introduction to Computing I (Winter 2009) Midterm Examination

Do not open this examination paper until instructed to do so. Answer all the questions.

CS S-20 Linked Lists III 1. We can then use the next pointer of the previous node to do removal (example on board)

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Linked Lists

public static boolean isoutside(int min, int max, int value)

Java Errors and Exceptions. Because Murphy s Law never fails

Transcription:

Linked Lists Since a variable referencing an object just holds the address of the object in memory, we can link multiple objects together to form dynamic lists or other structures. In our case we will make a list. The advantage of forming lists this way is we will only use exactly the amount of storage space that is needed to hold the number of items in the list, unlike an array (or even ArrayList) which could waste some memory. We define a record (called a node) that has at least two class variables: next (a pointer or reference to the next node in the list) and component (the type of the items on the list). For example, let's assume that our list is a list of integers. public class Node public Node() num = 0; next = null; public Node(int num) this.num = num; next = null; public int getnum() return num; public Node getnext() return next; public void setnum(int n) num = n; public void setnext(node next) this.next = next; private int num; // payload for the node private Node next; // pointer to the next node in the list

To form a dynamic linked list, we link variables of Node together to form a chain using the next data variable. We can start by making two Node objects: public static void main(string[] args) Node head = null; // First thing in the list Node othernode = null; head = new Node(10); othernode = new Node(20); Right now we have two separate Nodes. We can link them together to form a linked list by having the next field of one pointing the address of the next node: head.setnext(othernode); We now have a picture that looks like: We just built a linked list consisting of two elements! The end of the list is signified by the next field holding null. We can get a third node and store its address in the next member of the second node. This process continues until the list is complete. The following code fragment reads and stores integer numbers into a list until the input is 1. public static void main(string[] args) Scanner keyboard = new Scanner(System.in); Node head = null; // First thing in the list Node tail = null; // Last thing in the list Node othernode = null; Node tempnode = null; int num; head = new Node(); tail = head; System.out.println("Enter value for the first node");

num = keyboard.nextint(); head.setnum(num); System.out.println( "Enter values for remaining nodes, -1 to stop."); num = keyboard.nextint(); while (num!= -1) othernode = new Node(num); // new node with num tail.setnext(othernode); // link to end of list tail = othernode; // new tail num = keyboard.nextint(); // get next value This program (it is incomplete, we ll finish it below) first allocates memory for head and inputs a value into it. It then sets tail equal to head. tail will be used to track the end of the list while head will be used to track the beginning of the list. For example, let s say that initially we enter the value 10: Upon entering the loop, let s say that we enter 50 which is stored into num. First we create a new node, referenced by othernode, and store data into it: Then we link tail s next to othernode:

Finally we update tail to point to othernode since this has become the new end of the list: Let s say that the next number we enter is 23. We will repeat the process, first allocated a new node pointed to by othernode, and filling in its values: Then we link tail s next to othernode: Finally we update tail to point to the new end of the list, othernode: The process shown above continues until the user enters 1. Note that this allows us to enter an arbitrary number of elements, up until we run out of memory! This overcomes limitations with arrays where we need to pre-allocate a certain amount of memory (that may turn out later to be too small).

Lists of dynamic variables are traversed (nodes accessed one by one) by beginning with the first node and accessing each node until the next member of a node is null. The following code fragment prints out the values in the list. System.out.println("Printing out the list"); tempnode = head; while (tempnode!= null) System.out.println(tempNode.getNum()); tempnode = tempnode.getnext(); tempnode is initialized to head, the first node. If tempnode is null, the list is empty and the loop is not entered. If there is at least one node in the list, we enter the loop, print the member component of tempnode, and update tempnode to point to the next node in the list. tempnode is null when the last number has been printed, and we exit the loop. Because the types of a list node can be any data type, we can create an infinite variety of lists. Pointers also can be used to create very complex data structures such as stacks, queues, and trees that are the subject of more advanced computer science courses. To try: Create a class that uses a linked list internally to provide the following functionality: MyStringList addstring(string s) deletestring(string s) boolean contains(string s) void output() - adds s to the front of the list - removes first s from the list - true if s is in the list - print out everything in the list This would be a good candidate to make into a template so we could make a list of any type instead of only strings! Something to think about and perhaps try: create a doubly-linked list, which has references to the previous and to the next Node in the list; this should make it easier to delete from the list, but there is more to update when we add to the list.