Introduction to Linked Lists

Similar documents
Linked Lists in C and C++

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

Lecture 4: Outline. Arrays. I. Pointers II. III. Pointer arithmetic IV. Strings

Data Structure Series

Introduction to Linked List: Review. Source:

+ Abstract Data Types

CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays

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

Module 11. Collections and Iterators. Adapted from Absolute Java, Rose Williams, Binghamton University

Data Structure. Recitation III

CS162 - POINTERS. Lecture: Pointers and Dynamic Memory

Lecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions?

ECE 2400 Computer Systems Programming Fall 2017 Topic 7: C Lists and Vectors

Heap Arrays and Linked Lists. Steven R. Bagley

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

Data Structures and Algorithms for Engineers

C++ for Java Programmers

Arrays, Pointers and Memory Management

Scott Gibson. Pointers & Dynamic Memory. Pre & Co Requisites. Random Access Memory. Data Types. Atomic Type Sizes

However, in C we can group related variables together into something called a struct.

CP2 Revision. theme: dynamic datatypes & data structures

ECE 2400 Computer Systems Programming, Fall 2018 PA2: List and Vector Data Structures

CS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018

DECLARAING AND INITIALIZING POINTERS

ECE 2400 Computer Systems Programming, Fall 2017 Programming Assignment 2: List and Vector Data Structures

CS 237 Meeting 19 10/24/12

Pointers, Dynamic Data, and Reference Types

CS107 Handout 13 Spring 2008 April 18, 2008 Computer Architecture: Take II

Language comparison. C has pointers. Java has references. C++ has pointers and references

Data Structures and Algorithms for Engineers

Robust Programming. Style of programming that prevents abnormal termination and unexpected actions

C Pointers. Indirection Indirection = referencing a value through a pointer. Creating Pointers. Pointer Declarations. Pointer Declarations

Assist. Prof. Dr. Caner ÖZCAN

Recitation #11 Malloc Lab. November 7th, 2017

Declaring Pointers. Declaration of pointers <type> *variable <type> *variable = initial-value Examples:

UNIT-I Fundamental Notations

Ashish Gupta, Data JUET, Guna

Functions in C C Programming and Software Tools

5 Phases of Software Life Cycle

Kurt Schmidt. October 30, 2018

The Java Collections Framework and Lists in Java Parts 1 & 2

Procedural programming with C

ECE 2035 Programming HW/SW Systems Spring problems, 5 pages Exam Three 8 April Your Name (please print clearly)

Unit IV & V Previous Papers 1 mark Answers

Data Structures in C. C Programming and Software Tools. N.C. State Department of Computer Science

Pointers. A pointer value is the address of the first byte of the pointed object in the memory. A pointer does not know how many bytes it points to.

ADT: Design & Implementation

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

Darshan Institute of Engineering & Technology for Diploma studies Unit 4

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

UEE1302 (1102) F10 Introduction to Computers and Programming (I)

FUNCTIONS POINTERS. Pointers. Functions

Singly (Simply) Linked Lists

Homework #3 CS2255 Fall 2012

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

REFERENCES, POINTERS AND STRUCTS

COMP26120: Pointers in C (2018/19) Lucas Cordeiro

Linked Lists Structures

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

CS61, Fall 2012 Section 2 Notes

Memory and Addresses. Pointers in C. Memory is just a sequence of byte-sized storage devices.

Linked List in Data Structure. By Prof. B J Gorad, BECSE, M.Tech CST, PHD(CSE)* Assistant Professor, CSE, SITCOE, Ichalkaranji,Kolhapur, Maharashtra

EL2310 Scientific Programming

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

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

Self-referential Structures and Linked List. Programming and Data Structure 1

Contents of Lecture 3

ECE 15B COMPUTER ORGANIZATION

Procedural Programming & Fundamentals of Programming

Dynamically Allocated Memory in C

Lecture 2: C Programm

Chapter-11 POINTERS. Important 3 Marks. Introduction: Memory Utilization of Pointer: Pointer:

Lab 4 - Linked Lists

by Pearson Education, Inc. All Rights Reserved.

Introduction to Programming in C Department of Computer Science and Engineering

CS 61c: Great Ideas in Computer Architecture

Section - Computer Science. int main() {! int a=10,b=20;! printf("a:%d B:%d\n",a,b);! a=(a+b)-(b=a);! printf("a:%d B:%d\n",a,b);!

Pointers. Memory. void foo() { }//return

CS113: Lecture 9. Topics: Dynamic Allocation. Dynamic Data Structures

2. List Implementations (a) Class Templates (b) Contiguous (c) Simply Linked (d) Simply Linked with Position Pointer (e) Doubly Linked

Linked Structures in C

Final CSE 131B Spring 2005

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

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

CMSC 202H. Containers and Iterators

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

Algorithms & Data Structures

MARKS: Q1 /20 /15 /15 /15 / 5 /30 TOTAL: /100

BBM 201 DATA STRUCTURES

JTSK Programming in C II C-Lab II. Lecture 3 & 4

Pointers. Lecture 1 Sections Robb T. Koether. Hampden-Sydney College. Wed, Jan 14, 2015

Elementary Data Structures: Part 1: Arrays, Lists. CSE 2320 Algorithms and Data Structures Vassilis Athitsos University of Texas at Arlington

Object-oriented Programming for Automation & Robotics Carsten Gutwenger LS 11 Algorithm Engineering

Java and C CSE 351 Spring

QUIZ How do we implement run-time constants and. compile-time constants inside classes?

Outline. iterator review iterator implementation the Java foreach statement testing

LINKED LIST IMPLEMENTATION USING C LANGUAGE: A REVIEW

CS61C : Machine Structures

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

C Praktikum. Advanced Pointers. Eugen Betke, Nathanael Hübbe, Michael Kuhn, Jakob Lüttgau, Jannek Squar

Transcription:

Introduction to Linked Lists In your previous programming course, you organized and processed data items sequentially using an array (or possibly an arraylist, or a vector). You probably performed several operations on arrays, such as sorting, inserting, deleting, and searching. If data items are not sorted, then searching for an item in the array can be very timeconsuming, especially with large arrays.

Introduction to Linked Lists Once the data items are sorted, we can use a binary search and improve the search algorithm; however, insertion and deletion become timeconsuming, especially with large arrays, because these operations require data movement. With an array of fixed size, new items can be added only if there is room. Thus, there are limitations when organizing data in an array.

Introduction to Linked Lists One way to improve performance when there is a need to insert and/or delete items is to use a data structure that is not contiguous in memory, such as a linked list.

Linked Lists a data structure in which each element is dynamically allocated and in which elements point to each other to define a linear relationship. elements are allocated separately and only when needed elements are usually the same type (but not always)

Linked Lists each element of the structure is typically called a node Example of a singly-linked list with a head pointer. Nodes are added to the front of the list. - indicates that the pointer is NULL

Introduction to Linked Lists Example of a singly-linked list with a head and tail pointer. Nodes can be added to the front or the end of the list.

Comparing Arrays and Linked Lists Both arrays and linked lists can be used to store linear data of similar types, but they both have some advantages and disadvantages over each other. Advantages of Arrays: We can randomly access an element of an array by using its index. When sorted, we can use a binary search to improve the searching algorithm

Comparing Arrays and Linked Lists Disadvantage of Arrays: The size of an array is fixed: So we must know the upper limit on the number of elements in advance. Generally, the allocated memory is equal to the upper limit irrespective of the usage In practical uses, upper limit is rarely reached; therefore wasted memory. With an array of fixed size, new items can be added only if there is room.

Comparing Arrays and Linked Lists Disadvantage of Arrays: Inserting new elements is time-consuming, because room has to be created for the new elements and, to create room, existing elements have to be shifted (see zybooks 7.2 regarding vectors). Deleting elements is time-consuming, if deleting elements not at the end of the array. e.g., to delete the i th element, everything after the i th element must be shifted up.

Comparing Arrays and Linked Lists Advantages of Linked Lists: We can increase the size of the linked list one item at a time, dynamically. We can easily insert elements in a linked list. We can easily delete elements from a linked list.

Comparing Arrays and Linked Lists Disadvantages of Linked Lists: Random access is not allowed. We have to access elements sequentially, starting from the first node. So we cannot do binary search with linked lists. Require extra memory space for a pointer in each node of the list.

Introduction to Linked Lists Types of Linked Lists A singly linked list as previously described A doubly linked list - a list that has two references, one to the node and another to the previous node. 1 2 7 3

Singly Linked List typedef struct listitemtype { type ; struct listitemtype *; }listitem; listitem *head;

Adding an Item to a List listitem *p, *q; Add an item pointed to by q after item pointed to by p Neither p nor q is NULL

Adding an Item to a List listitem *addafter(listitem *p, listitem *q){ q -> = p -> ; p -> = q; return p; }

Adding an Item to a List listitem *addafter(listitem *p, listitem *q){ q -> = p -> ; p -> = q; return p; }

Adding an Item to a List listitem *addafter(listitem *p, listitem *q){ q -> = p -> ; p -> = q; return p; } Question: What should we do if we cannot guarantee that p and q are non-null?

Adding an Item to a List (continued) listitem *addafter(listitem *p, listitem *q){ if (p && q) { q -> = p -> ; p -> = q; } return p; }

What about Adding an Item before another Item? struct listitem *p; Add an item before item pointed to by p (p!= NULL)

What about Adding an Item before another Item? Answer: Need to search list from beginning to find previous item Add new item after previous item

Linked Lists (continued) We want to develop a list management system that allows us to maintain lists of any type of data (integers, floats, structures, etc.). We will use void pointers to accomplish this.

A review of void Pointers and type casting A void pointer (i.e., void *) is a generic pointer that can hold the address of any pointer type. Consider the following segment of code on the right: Example: int x; float y; typedef struct datatype { int f1; int f2; } data_t; data_t d1; data_t *dptr; void *ptr; The void pointer ptr can be set to point to any of the objects, and any type pointer can be set to ptr ptr = &x; ptr = &y; ptr = &d1; ptr = dptr; dptr = ptr;

A review of void Pointers and type casting Although a void * can be set to point to any type, you should not assign a pointer to a given type to a pointer to another type. Consider the code on the right int x = 55; float y = 83.7; int *iptr; int *fptr = &y; iptr = fptr; Note that iptr is a pointer to an int and y is a float You will get the following message : warning: assignment from incompatible pointer type and generally unexpected behavior.

A review of void Pointers and type casting You can never dereference a void pointer. i.e., void * pointers can never be directly used to access the memory to which they point because the size and type of the location are unknown. Example: int x; float y; typedef struct datatype { int f1; int f2; } data_t; data_t d1; data_t *dptr; void *ptr; x = *ptr; warning: dereferencing 'void *' pointer error: invalid use of void expression

A review of void Pointers and type casting There are two ways to avoid this problem: 1. type casting: You can tell the compiler the type of the data that ptr is pointing to, i.e.: x = *(int *)ptr; This is telling the compiler to treat ptr as a pointer to something of type int, and then copy the integer contents it is "pointing to" to x. 2. Define a separate integer pointer and copy ptr to it; the other technique is to simply define another pointer, i.e.: int *intptr; intptr = ptr; x = *intptr;

A review of void Pointers and type casting Defining a few extra pointers of the appropriate type may result in more readable code and will likely be less errorprone (but either approach is okay). Here is another example using the structure on the right. Assume we want to set the f2 field in d1. Note: ptr is pointing to d1 Example: int x; float y; typedef struct data_type { int f1; int f2; } data_t; data_t d1; data_t *dptr; void *ptr = &d1; /* set f2 field in d1 */ ((data_t *)ptr)->f2 = 6; /* or */ dptr = ptr; dptr->f2 = 6;

Linked List (continued) A linked list is a very useful data structure and many of the techniques used to manipulate linked lists are applicable to other data structures. In lab, you will develop a list management module.

List data structures The node_t structure The following example creates a new type name, node_t, which is 100% equivalent to struct node_type /** List node **/ typedef struct node_type { struct node_type *; /* Pointer to node */ void *dataptr; /* Pointer to associated object */ } node_t; There is a single instance of the node_t structure for each element in each list. Note: we must use the "official" name struct node_type when declaring because node_t is not known to be a type definition until 3 lines later! Each node contains two pointers: One is to the node_t in the list. The other points to the actual data being managed by the list

List data structures The node_t structure /** List node **/ typedef struct node_type { struct node_type *; /* Pointer to node */ void *dataptr; /* Pointer to associated object */ } node_t; The dataptr pointer is declared to be of type void *. As stated earlier, A void * pointer is a pointer to something of unknown or generic type. void * pointers can be freely assigned to other pointers void * pointers can never be directly used to access the memory to which they point because the size and type of the location are unknown.

List data structures /** List structures **/ typedef struct list_type { node_t *head; /* Pointer to front of list */ } list_t; There is a single instance of the list_t structure for each list.

list_t Functions newlist() a function used to create a new list. In a true O-O language, each class has a constructor method that is automatically invoked when a new instance of the class is created. The newlist() function serves this role here. Its mission is to: 1 - malloc() a new list_t structure. 2 - set the head pointer of the structure to NULL. 3 - return a pointer to the list_ to the caller. list_t *newlist() { }

list_t Functions list_add() - must add the element pointed to by objptr to the list structure pointed to by list. Its mission is to: 1. malloc() a new instance of node_t, 2. assign dataptr to the dataptr of the new node_t 3. add the new node_ to the front of the list, i.e. a. assign the pointer of the new node to point to what head is pointing to, and b. assign head to point to the new node_t void list_add(list_t *list, void *dataptr) {

Processing a list the iterator_t object The list_t functions described above provide a means to add nodes to the list, but there are no functions to process the nodes of a list (i.e. retrieve the nodes). Both Java and C++ provide another class known as the iterator class that is associated with a list and can be used to sequentially retrieve elements of a list. We will develop our own version of an iterator.

Processing a list the iterator_t object /** Iterator **/ typedef struct list_iterator { list_t *list; /* List iterator is associated with */ node_t *position; /* Current position in list */ } iterator_t; The list field points to the list_t the iterator is associated with, and position points to the node that would be retrieved.

list_t Functions iterator_t *newiterator(list_t *list); list_reset() sets the position pointer to the head pointer. If the list is empty this will cause the position pointer to be set to NULL. /* Reset position to front of list */ void list_reset(iterator_t *iter) { }

list_t Functions list_has() tests for the end of the list. Returns 1 if not at the end of the list; otherwise returns 0. int list_has(iterator_t *iter) { } The list_has() function should be called BEFORE list_() is invoked to make sure the current pointer points to a valid node!

list_t Functions list_() returns the address of the data pointed to by the node to which the position pointer points. The function should advance the position pointer so that it points to the node in the list. If the position pointer is presently pointing at the last node in the list, then this call will and should set the current pointer to NULL. void *list_(iterator_t *iter) { }