Linked List Alternate approach to maintaining an array of elements Rather than allocating one large group of elements, allocate elements as needed Q: how.

Slides:



Advertisements
Similar presentations
Linked Lists Geletaw S..
Advertisements

Linked Lists CS-212 Dick Steflik. Linked Lists A sequential collection of information Can be unordered; i.e. in no specific order Can be ordered; may.
Stacks, Queues, and Linked Lists
Linked Lists.
Chapter 3 – Lists A list is just what the name implies, a finite, ordered sequence of items. Order indicates each item has a position. A list of size 0.
Data Structures Linked Lists Linked List Basics. Array Disadvantages Arrays, although easy to understand have lots of disadvantages Contiguous Memory.
Linked Lists CSE 2451 Matt Boggus. Dynamic memory reminder Allocate memory during run-time malloc() and calloc() – return a void pointer to memory or.
418115: II. Linked List A linked list can be thought of a chain of linked list elements. A linked list element contains a single data item, and contains.
LIST PROCESSING.
Singly Linked List BTECH, EE KAZIRANGA UNIVERSITY.
Computer Programming for Engineering Applications ECE 175 Intro to Programming.
Linked List Variations
Data Structure Lecture-5
Data Structure Lecture-3 Prepared by: Shipra Shukla Assistant Professor Kaziranga University.
Linked Lists CENG 213 Data Structures.
Senem Kumova Metin Spring2009 STACKS AND QUEUES Chapter 10 in A Book on C.
Chapter 6 Data Types
Introduction to Linked Lists In your previous programming course, you saw how data is organized and processed sequentially using an array. You probably.
David Notkin Autumn 2009 CSE303 Lecture 13 This space for rent.
C Intro.
Chapter 17 Linked List Saurav Karmakar Spring 2007.
M180: Data Structures & Algorithms in Java
Computer Programming Link List (Insertion, Printing and Deletion functions) Lecture 23.
Programming Linked Lists. COMP104 Linked Lists / Slide 2 Motivation * A “List” is a useful structure to hold a collection of data. n Currently, we use.
Chapter 12 C Data Structures Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
1 Data Structures Data Structures Topic #2. 2 Today’s Agenda Data Abstraction –Given what we talked about last time, we need to step through an example.
Chapter 12 Data Structure Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 15: Linked data structures.
 2007 Pearson Education, Inc. All rights reserved C Data Structures.
Introduction to Data Structures Systems Programming.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
Introduction to Data Structures Systems Programming Concepts.
Lists Chapter 8. 2 Linked Lists As an ADT, a list is –finite sequence (possibly empty) of elements Operations commonly include: ConstructionAllocate &
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
APS105 Lists. Structures Arrays allow a collection of elements –All of the same type How to collect elements of different types? –Structures; in C: struct.
Computer Programming for Engineering Applications ECE 175 Intro to Programming.
Data Structures. Abstract Data Type A collection of related data is known as an abstract data type (ADT) Data Structure = ADT + Collection of functions.
Simulated Pointers Limitations Of C++ Pointers May be used for internal data structures only. Data structure backup requires serialization and deserialization.
CS261 Data Structures Linked Lists - Introduction.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
1 Linked List. Outline Introduction Insertion Description Deletion Description Basic Node Implementation Conclusion.
1 Linked List. 2 List A list refers to a sequence of data items  Example: An array The array index is used for accessing and manipulation of array elements.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Linked Lists Outline Introduction Self-Referential Structures.
Doubly Linked List Exercises Sometimes it is useful to have a linked list with pointers to both the next and previous nodes. This is called a doubly 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 Tutorial - Pointers CS 537 – Introduction to Operating Systems.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
(1-3) Basics of a Linked List I Instructor - Andrew S. O’Fallon CptS 122 (June 9, 2016) Washington State University.
Chapter 12 – Data Structures
Dynamic Allocation Review Structure and list processing
Linked List :: Basic Concepts
Introduction to Linked Lists
UNIT – I Linked Lists.
Linked Lists Chapter 6 Section 6.4 – 6.6
12 C Data Structures.
Lecture - 6 On Data Structures
Data Structures and Algorithms
CSE 143 Linked Lists [Chapter , 8.8] 3/30/98.
Stack and Queue APURBO DATTA.
(2-1) Data Structures & The Basics of a Linked List I
Linked List Sudeshna Sarkar.
Prof. Neary Adapted from slides by Dr. Katherine Gibson
(2-1) Data Structures & The Basics of a Linked List I
Review & Lab assignments
Data Structures and Algorithms
Linked List.
Linked Lists Adapted from Dr. Mary Eberlein, UT Austin.
17CS1102 DATA STRUCTURES © 2018 KLEF – The contents of this presentation are an intellectual and copyrighted property of KL University. ALL RIGHTS RESERVED.
EECE.3220 Data Structures Instructor: Dr. Michael Geiger Spring 2019
Linked Lists.
Presentation transcript:

Linked List Alternate approach to maintaining an array of elements Rather than allocating one large group of elements, allocate elements as needed Q: how do we know what is part of the array? A: have the elements keep track of each other –use pointers to connect the elements together as a LIST of things

Outline Linked list basic terms (data, link, node) type definition visualization operations init, insert, read group, find, print, delete, sort variations dummy head node sorted list

Limitation of Arrays An array has a limited number of elements –routines inserting a new value have to check that there is room Can partially solve this problem by reallocating the array as needed (how much memory to add?) –adding one element at a time could be costly –one approach - double the current size of the array A better approach: use a Linked List

Dynamically Allocating Elements Allocate elements one at a time as needed, have each element keep track of the next element Result is referred to as linked list of elements, track next element with a pointer

Linked List Notes Need way to indicate end of list (NULL pointer) Need to know where list starts (first element) Each element needs pointer to next element (its link) Need way to allocate new element (use malloc) Need way to return element not needed any more (use free) Divide element into data and pointer

Linked List Type Type declaration: typedef struct ESTRUCT { DataType data; /* DataType is type for element of list */ struct ESTRUCT *next; } EStruct, *EPtr; Pointer to first element: EPtr ListStart; /* ListStart points to first element of list *ListStart is first element struct ListStart->data is data of first element ListStart->next points to second element */

Sample Linked List Operations void main() { /* Assume data is int */ EPtr ListStart = NULL; /* safest to give ListStart an initial legal value -- NULL indicates empty list */ ListStart = (EPtr) malloc(sizeof(EStruct)); /* ListStart points to memory allocated at location 108 */

Sample Linked List Ops (cont) ListStart->data = 5; ListStart->next = (EPtr) malloc(sizeof(EStruct)); ListStart->next = NULL; ListStart->next->data = 9; ListStart->next->next = NULL;

Sample Linked List Ops (cont) ListStart->next->next = (EPtr) malloc(sizeof(EStruct)); ListStart->next->next->data = 6; ListStart->next->next->next = NULL; /* Linked list of 3 elements (count data values): ListStart points to first element ListStart->next points to second element ListStart->next->next points to third element and ListStart->next->next->next is NULL to indicate there is no fourth element */

Sample Linked List Ops (cont) /* To eliminate element, start with free operation */ free(ListStart->next->next); /* NOTE: free not enough -- does not change memory Element still appears to be in list But C might give memory away in next request Need to reset the pointer to NULL */ ListStart->next->next = NULL; /* Element at 132 no longer part of list (safe to reuse memory) */

Common Mistakes Dereferencing a NULL pointer ListStart = NULL; ListStart->data = 5; /* ERROR */ Using a freed element free(ListStart->next); ListStart->next->data = 6; /* PROBLEM */ Using a pointer before set ListStart = (EPtr) malloc(sizeof(EStruct)); ListStart->next->data = 7; /* ERROR */

List Initialization Certain linked list ops (init, insert, etc.) may change element at start of list (what ListStart points at) –to change what ListStart points to could pass a pointer to ListStart (pointer to pointer) –alternately, in each such routine, always return a pointer to ListStart and set ListStart to the result of function call (if ListStart doesnt change it doesnt hurt) EPtr initList() { return NULL; } ListStart = initList();

A Helper Function Build a function used whenever a new element is needed (function always sets data, next fields): EPtr newElement(DataType ndata, EPtr nnext) { EPtr newEl = (EPtr) malloc(sizeof(EStruct)); newEl->data = ndata; newEl->next = nnext; return newEl; }

List Insertion (at front) Add new element to list: –Make new elements next pointer point to start of list –Make pointer to new element start of list EPtr insertF(EPtr start, DataType dnew) { return newElement(dnew,start); } –To use, get new value to add (ask user, read from file, whatever), then call insertF: ListStart = insertF(ListStart,NewDataValue);

Insert at Front Example

Insert at Front (Again)

Insert at End Need to find end of list -- use walker (temporary pointer) to walk down list EPtr insertE(EPtr start, DataType dnew) { EPtr last = start; /* Walker */ if (start == NULL) /* if list empty, add at */ return newElement(dnew,NULL); /* start */ else { while (last->next != NULL) /* stop at */ last = last->next; /* last item */ last->next = newElement(dnew,NULL); return start; /* start doesnt change */ }

Insert at End Example

Reading a Group of Elements EPtr readGroup(EPtr start, FILE *instream) { DataType dataitem; while (readDataSucceeds(instream,&dataitem)) /* Add new item at beginning */ start = newElement(dataitem,start); return start; } /* Assume DataType is int: */ int readDataSucceeds(FILE *stream, int *data) { if (fscanf(stream,%d,data) == 1) return 1; else return 0; }

Reading Group - Add at End EPtr readGroupE(EPtr start, FILE *instream) { EPtr last; DataType data; /* Try to get first new item */ if (!readDataSucceeds(instream,&data)) return start; /* if none, return initial list */ else { /* Add first new item */ if (start == NULL) { /* If list empty, first item is list start */ start = newElement(data,NULL); last = start; }

Reading Group - Add at End (cont) else { /* List not initially empty */ last = start; while (last->next != NULL) /* Find end */ last = last->next; /* Add first element at end */ last->next = newElement(data,NULL); last = last->next; } /* Add remaining elements */ while (readDataSucceeds(instream,&data)) { last->next = newElement(data,NULL); last = last->next; } return start; }

Printing a List Use a walker to examine list from first to last void printList(EPtr start) { EPtr temp = start; while (temp != NULL) { printData(temp->data); temp = temp->next; }

Finding an Element in List Return pointer to item (if found) or NULL (not found) EPtr findE(EPtr start, DataType findI) { EPtr findP = start; /* walker */ while ((findP != NULL) && (findP->data is not the same as findI)) findP = findP->next; return findP; }

Deleting an Element

Deletion Code EPtr delete(EPtr start, DataType delI) { EPtr prev = NULL; EPtr curr = start; while ((curr != NULL) && (curr->data is not delI)) { prev = curr; curr = curr->next; } if (curr == NULL) printf(Item to delete not found\n); else { if (prev == NULL) start = start->next; else prev->next = curr->next; free(curr); } return start; }

Selection Sorting Linked List EPtr sort(EPtr unsorted) { EPtr sorted = NULL; EPtr largest, prev; while (unsorted != NULL) { prev = findItemBeforeLargest(unsorted); if (prev == NULL) { largest = unsorted; unsorted = unsorted->next; } else { largest = prev->next; prev->next = largest->next; } largest->next = sorted; sorted = largest; } return sorted; }

Item Before Largest EPtr findItemBeforeLargest(EPtr start) { EPtr prevlargest = NULL; EPtr largest = start; EPtr prev = start; EPtr curr = start->next; while (curr != NULL) { if (curr->data bigger than largest->data) { prevlargest = prev; largest = curr; } prev = curr; curr = curr->next; } return prevlargest; }

Linked List Variation: Dummy Head Node Why? –No special case for inserting/deleting at beginning –ListStart does not change after it is initialized Disadvantage –cost of one extra element

DH List Initialization/Insert EPtr initList() { EPtr ListStart = (EPtr) malloc(sizeof(EStruct)); ListStart->next = NULL; return ListStart; } void insertF(EPtr start, DataType dnew) { start->next = newElement(dnew,start->next); }

DH Inserting at End void insertE(EPtr start, DataType dnew) { EPtr last = start; /* Walker */ /* No special list is empty case */ while (last->next != NULL) last = last->next; last->next = newElement(dnew,NULL); }

DH Printing a List Have walker start at second element void printList(EPtr start) { EPtr temp = start->next; while (temp != NULL) { printData(temp->data); temp = temp->next; }

DH Deletion Code void delete(EPtr start, DataType delI) { EPtr prev = start; EPtr curr = start->next; while ((curr != NULL) && (curr->data is not delI)) { prev = curr; curr = curr->next; } if (curr == NULL) printf(Item to delete not found\n); else { prev->next = curr->next; free(curr); }

Linked List Variation: Sorted List Idea: keep the items on the list in a sorted order sort based on data value in each node advantages: already sorted operations such as delete, find, etc. need not search to the end of the list if the item is not in list disadvantages insert must search for the right place to add element (slower than simply adding at beginning)

Sorted Insert (with Dummy Head) void insertS(EPtr start, DataType dnew) { EPtr prev = start; EPtr curr = start->next; while ((curr != NULL) && (dnew is bigger than curr->data)) { prev = curr; curr = curr->next; } prev->next = newElement(dnew,curr); }