This document discusses search algorithms, including linear search and binary search. It covers:
1) Linear search sequentially scans an array to find a match, working for both sorted and unsorted arrays.
2) Binary search uses recursion to search a sorted array, eliminating half the search space each iteration, making it faster than linear search.
3) Implementation examples of linear and binary search in Java are provided, along with analysis of the time efficiency of each method.
The document discusses stacks and queues as abstract data types (ADTs). It describes common stack and queue operations like push, pop, enqueue, and dequeue. It provides examples of how stacks and queues can be used, such as checking for balanced parentheses with a stack and implementing a postfix calculator with a stack. The document also discusses different implementations of stacks and queues using arrays and linked lists.
This document discusses algorithm analysis and determining the time complexity of algorithms. It begins by defining an algorithm and noting that the efficiency of algorithms should be analyzed independently of specific implementations or hardware. The document then discusses analyzing the time complexity of various algorithms by counting the number of operations and expressing efficiency using growth functions. Common growth functions like constant, linear, quadratic, and exponential are introduced. The concept of asymptotic notation (Big O) for describing an algorithm's time complexity is also covered. Examples are provided to demonstrate how to determine the time complexity of iterative and recursive algorithms.
This document discusses trees and binary trees. It covers tree terminology, tree traversals including preorder, inorder and postorder, implementing binary trees in Java, using binary trees to represent general trees, and applications of trees for data science. The next lecture will cover binary search trees, AVL trees, binary heaps and red black trees.
The document discusses minimum spanning trees and provides examples of Prim's and Kruskal's algorithms. It includes:
- A definition of minimum spanning tree as a subgraph that spans all nodes with minimum total edge weight.
- Characteristics of Prim's and Kruskal's algorithms such as working with undirected, weighted/unweighted graphs and producing optimal solutions greedily.
- A walk-through example of Prim's algorithm on a graph and calculating the minimum spanning tree cost.
This document discusses AVL trees, which are self-balancing binary search trees. It covers:
- AVL trees maintain balance by ensuring the heights of left and right subtrees differ by at most one.
- Insertion and deletion may cause imbalance, requiring single or double rotations to rebalance the tree.
- Insertion can cause two types of imbalance fixed by single or double rotations respectively. Deletion is similar but allows propagating rotations to reduce rotations.
- Pseudocode and Java code examples are provided for AVL tree insertion, deletion, and rebalancing rotations.
The document discusses a lecture on red-black trees, which are self-balancing binary search trees. It provides an overview of red-black trees, including that they ensure the tree is balanced so that operations take O(log n) time. The lecture covers red-black trees and their implementation in Java. Next week will include a midterm exam on the material covered so far.
This document discusses search algorithms, including linear search and binary search. It covers:
1) Linear search sequentially scans an array to find a match, working for both sorted and unsorted arrays.
2) Binary search uses recursion to search a sorted array, eliminating half the search space each iteration, making it faster than linear search.
3) Implementation examples of linear and binary search in Java are provided, along with analysis of the time efficiency of each method.
The document discusses stacks and queues as abstract data types (ADTs). It describes common stack and queue operations like push, pop, enqueue, and dequeue. It provides examples of how stacks and queues can be used, such as checking for balanced parentheses with a stack and implementing a postfix calculator with a stack. The document also discusses different implementations of stacks and queues using arrays and linked lists.
This document discusses algorithm analysis and determining the time complexity of algorithms. It begins by defining an algorithm and noting that the efficiency of algorithms should be analyzed independently of specific implementations or hardware. The document then discusses analyzing the time complexity of various algorithms by counting the number of operations and expressing efficiency using growth functions. Common growth functions like constant, linear, quadratic, and exponential are introduced. The concept of asymptotic notation (Big O) for describing an algorithm's time complexity is also covered. Examples are provided to demonstrate how to determine the time complexity of iterative and recursive algorithms.
This document discusses trees and binary trees. It covers tree terminology, tree traversals including preorder, inorder and postorder, implementing binary trees in Java, using binary trees to represent general trees, and applications of trees for data science. The next lecture will cover binary search trees, AVL trees, binary heaps and red black trees.
The document discusses minimum spanning trees and provides examples of Prim's and Kruskal's algorithms. It includes:
- A definition of minimum spanning tree as a subgraph that spans all nodes with minimum total edge weight.
- Characteristics of Prim's and Kruskal's algorithms such as working with undirected, weighted/unweighted graphs and producing optimal solutions greedily.
- A walk-through example of Prim's algorithm on a graph and calculating the minimum spanning tree cost.
This document discusses AVL trees, which are self-balancing binary search trees. It covers:
- AVL trees maintain balance by ensuring the heights of left and right subtrees differ by at most one.
- Insertion and deletion may cause imbalance, requiring single or double rotations to rebalance the tree.
- Insertion can cause two types of imbalance fixed by single or double rotations respectively. Deletion is similar but allows propagating rotations to reduce rotations.
- Pseudocode and Java code examples are provided for AVL tree insertion, deletion, and rebalancing rotations.
The document discusses a lecture on red-black trees, which are self-balancing binary search trees. It provides an overview of red-black trees, including that they ensure the tree is balanced so that operations take O(log n) time. The lecture covers red-black trees and their implementation in Java. Next week will include a midterm exam on the material covered so far.
The document discusses data structures and algorithms. It defines data structures as organized ways of storing data to allow efficient processing. Algorithms manipulate data in data structures to perform operations like searching and sorting. Big-O notation provides an asymptotic analysis of algorithms, estimating how their running time grows with input size. Common time complexities include constant O(1), linear O(n), quadratic O(n^2), and exponential O(2^n).
The document discusses stacks as a data structure. It defines a stack as a list where all insertions and deletions are made at one end, called the top. Stacks follow the LIFO (last in, first out) principle. The document provides examples of stack implementations using arrays in C++ and describes the basic stack operations like push, pop, peek, and isEmpty. It also gives examples of real-world stacks like stacks of books, chairs, and cups.
This document provides an introduction and overview of data structures and algorithms. It begins by outlining the topics that will be covered, including data structures, algorithms, abstract data types, and object-oriented programming. It then defines what a data structure is and provides examples. Different types of data structures are discussed, including linear structures like lists, queues, and stacks, as well as non-linear structures like trees, graphs, and hash tables. The document also defines what an algorithm is and discusses why algorithms are important. It provides examples of successful algorithms and discusses the need for correctness and efficiency in algorithms. The relationship between programs, data structures, and algorithms is also briefly explained.
This document provides an overview of different searching techniques including sequential search, binary search, tree searching using binary search trees, hashing techniques, and general search trees. It defines key search terminology and summarizes algorithms for common search operations like search, insertion and deletion in various data structures that support efficient searching like binary search trees, B-trees, and hash tables. Examples are provided to illustrate search techniques and how they work.
This document discusses various sorting algorithms:
1) Insertion sort works by inserting elements into a sorted list one by one in linear time but has quadratic worst-case time complexity.
2) Shell sort improves on insertion sort by allowing elements far apart to be compared and improved to O(n^7/6) average time.
3) Merge sort works by recursively dividing the list into halves and merging the sorted halves together, providing O(n log n) time.
4) Quicksort and heapsort also provide O(n log n) time by partitioning elements.
5) Distribution sorts like radix and bucket sort use the element values to distribute into buckets in linear time if buckets are small.
The document discusses various sorting algorithms including exchange sorts like bubble sort and quicksort, selection sorts like straight selection sort, and tree sorts like heap sort. For each algorithm, it provides an overview of the approach, pseudocode, analysis of time complexity, and examples. Key algorithms covered are bubble sort (O(n2)), quicksort (average O(n log n)), selection sort (O(n2)), and heap sort (O(n log n)).
Tech Jobs Interviews Preparation - GeekGap Webinar #1
Part 1 - Algorithms & Data Structures
What is an algorithm?
What is a data structure (DS)?
Why study algorithms & DS?
How to assess good algorithms?
Algorithm & DS interviews structure
Case study: Binary Search
2 Binary Search variants
Part 2 - System Design
What is system design?
Why study system design?
System design interviews structure
Case study: ERD with Lucidchart
Demo Time: SQLAlchemy
Githu Repo: http://bit.ly/gg-io-webinar-1-github
by www.geekgap.io
This document provides a summary of a textbook on data structures and algorithms. It includes a preface describing the textbook's approach of presenting data structures within the context of assessing costs and benefits, understanding tradeoffs, learning common practices, and matching data structures to application needs. The preface also discusses how the textbook can be used in an advanced undergraduate course on data structures or algorithms.
9. Searching & Sorting - Data Structures using C++ by Varsha Patilwidespreadpromotion
The document discusses various searching and sorting algorithms. It covers sequential search, binary search, Fibonacci search, hashed search, indexed sequential search and their time complexities. Sorting algorithms like bubble sort, insertion sort, selection sort are explained along with their analysis. Internal sorting techniques like quicksort, heapsort, radix sort and bucket sort are also mentioned. The document provides details on sorting methods, order, stability and efficiency.
In this playlist
https://youtube.com/playlist?list=PLT...
I'll illustrate algorithms and data structures course, and implement the data structures using java programming language.
the playlist language is arabic.
The Topics:
--------------------
1- Arrays
2- Linear and Binary search
3- Linked List
4- Recursion
5- Algorithm analysis
6- Stack
7- Queue
8- Binary search tree
9- Selection sort
10- Insertion sort
11- Bubble sort
12- merge sort
13- Quick sort
14- Graphs
15- Hash table
16- Binary Heaps
Reference : Object-Oriented Data Structures Using Java - Third Edition by NELL DALE, DANEIEL T.JOYCE and CHIP WEIMS
Slides is owned by College of Computing & Information Technology
King Abdulaziz University, So thanks alot for these great materials
This document provides an introduction to data structures and algorithms. It defines data structures as organized collections of data and describes common types including primitive, non-primitive, linear, and non-linear data structures. It also defines algorithms as step-by-step problem solving processes and discusses characteristics like finite time completion. The document outlines ways to measure algorithm efficiency including time and space complexity and asymptotic notation.
This document discusses queues and their implementation using data structures in C++. It covers:
1) Defining queues and their operations of insertion at the rear and deletion at the front.
2) Implementing queues using arrays and avoiding their drawbacks using circular queues.
3) Other applications that use queues like simulation, job scheduling, and priority queues.
4) Different queue implementations like multi-queue, deque, and priority queue data structures.
The document discusses recursion in computer programming. It defines recursion as a function that calls itself or is called by another function. It categorizes different types of recursion such as direct, indirect, linear, tree, and tail recursion. It explains how recursive functions work by using a stack to store information from each function call. Examples of recursively-defined problems like factorials and Fibonacci numbers are provided. Guidelines for writing recursive functions and solving problems recursively are also outlined.
The document discusses stacks and their applications. It describes stacks as last-in, first-out data structures and covers stack operations like push and pop. Common uses of stacks include expression evaluation, recursion, reversing data structures, and printing job queues. The document also discusses time and space complexity analysis of algorithms, conversion between infix, postfix and prefix notation, and software engineering principles like the software development life cycle.
This document provides an introduction to data structures. It defines key terms like data, information, records and files. It also describes different types of data structures like arrays, linked lists, stacks, queues, trees and graphs. Linear and non-linear data structures are explained. Common operations on data structures like insertion, deletion and searching are outlined. The document also defines what an algorithm is and provides an example of an algorithm to add two numbers. It concludes by describing time and space complexity analysis of algorithms.
This document provides a step-by-step guide to learning R. It begins with the basics of R, including downloading and installing R and R Studio, understanding the R environment and basic operations. It then covers R packages, vectors, data frames, scripts, and functions. The second section discusses data handling in R, including importing data from external files like CSV and SAS files, working with datasets, creating new variables, data manipulations, sorting, removing duplicates, and exporting data. The document is intended to guide users through the essential skills needed to work with data in R.
Data Structures are the programmatic way of storing data so that data can be used efficiently
Introduction to DSA
Advantages & Disadvantages
Abstract Data Type (ADT)
Linear Array List
Downloadable Resources
This document provides an overview of a course on data structures and algorithm analysis. It introduces some key data structures like arrays, linked lists, stacks, and queues. It also discusses algorithm strategies such as brute force, greedy, and divide-and-conquer algorithms. The course contents are described, including reviewing programming concepts, fundamental data structures and algorithms, recursion, and more. Assessment includes assignments, quizzes, class tests, and a final exam. Common operations on data structures like traversal, insertion, deletion, and searching are explained.
The document discusses different data structures like arrays, linked lists, stacks, and queues, explaining what they are, common operations on them like searching and sorting, as well as examples of algorithms for implementing common operations like insertion and deletion on each data structure. Key data structures are explained along with their properties and typical applications.
This document summarizes the basics of linked lists, including how references to objects work in linked lists, traversing a linked list to access all nodes, and implementing common linked list operations like add, get, and add at a specific index. Key points covered include using a "current" reference to traverse the list without modifying the original reference, how to add nodes to an empty list versus a non-empty list, and how to insert nodes by modifying the next reference of the preceding node. Pseudocode is provided for linked list traversal and implementing the main linked list methods on a LinkedIntList class.
This document outlines a lab manual for a Data Structures and Algorithms course. The lab covers basic operations on arrays in C++, including insertion, deletion, traversal, and searching algorithms. It provides pseudocode and C++ code examples for inserting and deleting elements from an array, traversing a linear array, and using linear and binary search algorithms. The objectives are to understand array operations, write algorithms, and implement them in code using the Dev C++ tool.
The document discusses data structures and algorithms. It defines data structures as organized ways of storing data to allow efficient processing. Algorithms manipulate data in data structures to perform operations like searching and sorting. Big-O notation provides an asymptotic analysis of algorithms, estimating how their running time grows with input size. Common time complexities include constant O(1), linear O(n), quadratic O(n^2), and exponential O(2^n).
The document discusses stacks as a data structure. It defines a stack as a list where all insertions and deletions are made at one end, called the top. Stacks follow the LIFO (last in, first out) principle. The document provides examples of stack implementations using arrays in C++ and describes the basic stack operations like push, pop, peek, and isEmpty. It also gives examples of real-world stacks like stacks of books, chairs, and cups.
This document provides an introduction and overview of data structures and algorithms. It begins by outlining the topics that will be covered, including data structures, algorithms, abstract data types, and object-oriented programming. It then defines what a data structure is and provides examples. Different types of data structures are discussed, including linear structures like lists, queues, and stacks, as well as non-linear structures like trees, graphs, and hash tables. The document also defines what an algorithm is and discusses why algorithms are important. It provides examples of successful algorithms and discusses the need for correctness and efficiency in algorithms. The relationship between programs, data structures, and algorithms is also briefly explained.
This document provides an overview of different searching techniques including sequential search, binary search, tree searching using binary search trees, hashing techniques, and general search trees. It defines key search terminology and summarizes algorithms for common search operations like search, insertion and deletion in various data structures that support efficient searching like binary search trees, B-trees, and hash tables. Examples are provided to illustrate search techniques and how they work.
This document discusses various sorting algorithms:
1) Insertion sort works by inserting elements into a sorted list one by one in linear time but has quadratic worst-case time complexity.
2) Shell sort improves on insertion sort by allowing elements far apart to be compared and improved to O(n^7/6) average time.
3) Merge sort works by recursively dividing the list into halves and merging the sorted halves together, providing O(n log n) time.
4) Quicksort and heapsort also provide O(n log n) time by partitioning elements.
5) Distribution sorts like radix and bucket sort use the element values to distribute into buckets in linear time if buckets are small.
The document discusses various sorting algorithms including exchange sorts like bubble sort and quicksort, selection sorts like straight selection sort, and tree sorts like heap sort. For each algorithm, it provides an overview of the approach, pseudocode, analysis of time complexity, and examples. Key algorithms covered are bubble sort (O(n2)), quicksort (average O(n log n)), selection sort (O(n2)), and heap sort (O(n log n)).
Tech Jobs Interviews Preparation - GeekGap Webinar #1
Part 1 - Algorithms & Data Structures
What is an algorithm?
What is a data structure (DS)?
Why study algorithms & DS?
How to assess good algorithms?
Algorithm & DS interviews structure
Case study: Binary Search
2 Binary Search variants
Part 2 - System Design
What is system design?
Why study system design?
System design interviews structure
Case study: ERD with Lucidchart
Demo Time: SQLAlchemy
Githu Repo: http://bit.ly/gg-io-webinar-1-github
by www.geekgap.io
This document provides a summary of a textbook on data structures and algorithms. It includes a preface describing the textbook's approach of presenting data structures within the context of assessing costs and benefits, understanding tradeoffs, learning common practices, and matching data structures to application needs. The preface also discusses how the textbook can be used in an advanced undergraduate course on data structures or algorithms.
9. Searching & Sorting - Data Structures using C++ by Varsha Patilwidespreadpromotion
The document discusses various searching and sorting algorithms. It covers sequential search, binary search, Fibonacci search, hashed search, indexed sequential search and their time complexities. Sorting algorithms like bubble sort, insertion sort, selection sort are explained along with their analysis. Internal sorting techniques like quicksort, heapsort, radix sort and bucket sort are also mentioned. The document provides details on sorting methods, order, stability and efficiency.
In this playlist
https://youtube.com/playlist?list=PLT...
I'll illustrate algorithms and data structures course, and implement the data structures using java programming language.
the playlist language is arabic.
The Topics:
--------------------
1- Arrays
2- Linear and Binary search
3- Linked List
4- Recursion
5- Algorithm analysis
6- Stack
7- Queue
8- Binary search tree
9- Selection sort
10- Insertion sort
11- Bubble sort
12- merge sort
13- Quick sort
14- Graphs
15- Hash table
16- Binary Heaps
Reference : Object-Oriented Data Structures Using Java - Third Edition by NELL DALE, DANEIEL T.JOYCE and CHIP WEIMS
Slides is owned by College of Computing & Information Technology
King Abdulaziz University, So thanks alot for these great materials
This document provides an introduction to data structures and algorithms. It defines data structures as organized collections of data and describes common types including primitive, non-primitive, linear, and non-linear data structures. It also defines algorithms as step-by-step problem solving processes and discusses characteristics like finite time completion. The document outlines ways to measure algorithm efficiency including time and space complexity and asymptotic notation.
This document discusses queues and their implementation using data structures in C++. It covers:
1) Defining queues and their operations of insertion at the rear and deletion at the front.
2) Implementing queues using arrays and avoiding their drawbacks using circular queues.
3) Other applications that use queues like simulation, job scheduling, and priority queues.
4) Different queue implementations like multi-queue, deque, and priority queue data structures.
The document discusses recursion in computer programming. It defines recursion as a function that calls itself or is called by another function. It categorizes different types of recursion such as direct, indirect, linear, tree, and tail recursion. It explains how recursive functions work by using a stack to store information from each function call. Examples of recursively-defined problems like factorials and Fibonacci numbers are provided. Guidelines for writing recursive functions and solving problems recursively are also outlined.
The document discusses stacks and their applications. It describes stacks as last-in, first-out data structures and covers stack operations like push and pop. Common uses of stacks include expression evaluation, recursion, reversing data structures, and printing job queues. The document also discusses time and space complexity analysis of algorithms, conversion between infix, postfix and prefix notation, and software engineering principles like the software development life cycle.
This document provides an introduction to data structures. It defines key terms like data, information, records and files. It also describes different types of data structures like arrays, linked lists, stacks, queues, trees and graphs. Linear and non-linear data structures are explained. Common operations on data structures like insertion, deletion and searching are outlined. The document also defines what an algorithm is and provides an example of an algorithm to add two numbers. It concludes by describing time and space complexity analysis of algorithms.
This document provides a step-by-step guide to learning R. It begins with the basics of R, including downloading and installing R and R Studio, understanding the R environment and basic operations. It then covers R packages, vectors, data frames, scripts, and functions. The second section discusses data handling in R, including importing data from external files like CSV and SAS files, working with datasets, creating new variables, data manipulations, sorting, removing duplicates, and exporting data. The document is intended to guide users through the essential skills needed to work with data in R.
Data Structures are the programmatic way of storing data so that data can be used efficiently
Introduction to DSA
Advantages & Disadvantages
Abstract Data Type (ADT)
Linear Array List
Downloadable Resources
This document provides an overview of a course on data structures and algorithm analysis. It introduces some key data structures like arrays, linked lists, stacks, and queues. It also discusses algorithm strategies such as brute force, greedy, and divide-and-conquer algorithms. The course contents are described, including reviewing programming concepts, fundamental data structures and algorithms, recursion, and more. Assessment includes assignments, quizzes, class tests, and a final exam. Common operations on data structures like traversal, insertion, deletion, and searching are explained.
The document discusses different data structures like arrays, linked lists, stacks, and queues, explaining what they are, common operations on them like searching and sorting, as well as examples of algorithms for implementing common operations like insertion and deletion on each data structure. Key data structures are explained along with their properties and typical applications.
This document summarizes the basics of linked lists, including how references to objects work in linked lists, traversing a linked list to access all nodes, and implementing common linked list operations like add, get, and add at a specific index. Key points covered include using a "current" reference to traverse the list without modifying the original reference, how to add nodes to an empty list versus a non-empty list, and how to insert nodes by modifying the next reference of the preceding node. Pseudocode is provided for linked list traversal and implementing the main linked list methods on a LinkedIntList class.
This document outlines a lab manual for a Data Structures and Algorithms course. The lab covers basic operations on arrays in C++, including insertion, deletion, traversal, and searching algorithms. It provides pseudocode and C++ code examples for inserting and deleting elements from an array, traversing a linear array, and using linear and binary search algorithms. The objectives are to understand array operations, write algorithms, and implement them in code using the Dev C++ tool.
DS Complete notes for Computer science and EngineeringRAJASEKHARV8
The document provides information about data structures using C programming language. It discusses various topics like arrays, linked lists, stacks, queues, trees and graphs. It provides the syllabus, contents and references for the course on data structures. The document contains lecture notes on different data structure topics with examples and algorithms for common operations like search, insertion, deletion on arrays and linked lists.
The document discusses various data structures for implementing lists, including array-based and pointer-based implementations. It describes list operations like insert, find, and delete. For pointer-based lists, it covers issues like using a header node, doubly linked lists, and circularly linked lists. The document also discusses implementing polynomials as linked lists sorted by exponent and sorting algorithms like bucket sort and radix sort.
Can somebody solve the TODO parts of the following problem- Thanks D.pdfvinaythemodel
Can somebody solve the TODO parts of the following problem.
Thanks
Description
This assignment builds on top of the ListNode class designed and tested in Assignment 4 where
constructionand testing of the ListNode class has already been done. Recall that a ListNode
object contains a data field and a pointer to the next ListNode object.
We now encapsulate the functions to create, search and update the database into a LinkedList
class. There are two members in this class. A pointer called front that points to a ListNode object
and an integer count of the total number of objects currently in the list.
As before, we are not going to use pre-fabricated classes from the c++ library, but construct the
LinkedList ADT from scratch.
We can now use this class to create a LinkedList object which contains a collection of ListNodes
each having a Song object in the data field. The api is put through its paces by initially testing it
on a dummy database containing four songs. The main program then repeats the testing process
with the song list in the file SongData.txt and then again with the song list in the file
SongDataDouble.txt.
The number of steps taken to populate the database for both files is recorded.
Instruction
#This assignment requires you to
Read the Assignment 5 Notes
Watch the Assignment 5 Support video
Implement the following methods of the LinkedList class
-custom constructor
-setters for next pointer and data
Implement the insert, remove and get method in the LinkedListcpp.h file
Scan the given template to find the above //TODO and implement the code needed
//Requires: Song for inserting
//Effects: creates a new ListNode with input value and inserts in proper position (increasing order
of chart position)in the chain. If LinkedList, adds to the beginning
//Modifies: front, if node is added at the beginning.
//Also changes the next pointer of the previous node to point to the newly inserted list node. the
next pointer of the newly inserted pointer points to what was the next of the previous node. This
way both previous and current links are adjusted
//TODO
template <class T>
int LinkedList<T>::insert( T value, SortBy<T> f){
int steps=0;
//TODO
return steps;
}
//Requires: Song title for searching
//Effects: traverses the LinkedList (database) starting from front until the end comparing titles
Returns the original search value if found otherwise returns an empty song with blank title
//Modifies: Nothing
//TODO
template <class T>
T LinkedList<T>::get(T value){
ListNode<T> * current = front;//this may need to change
//TODO
return current->getData();
}
//TODO
template <class T>
int LinkedList<T>::remove(T value){
//TODO
int steps=0;
return steps;
}
/ /Requires: index position of Song to be found
//Effects: traverses the LinkedList starting from front and travels to the index position (if valid)
and returns the song at that index position. Note index position may NOT be the same as chart
position
//Modifies: Nothing
//TODO
template <class T>
T Linke.
The document outlines the key concepts of linked lists including:
- Linked lists allow for dynamic resizing and efficient insertion/deletion unlike arrays.
- A linked list contains nodes that have a data field and a pointer to the next node.
- Common operations on linked lists include insertion, deletion, searching, and traversing the list.
- The time complexity of these operations depends on whether it's at the head, tail, or interior node.
- Linked lists can be implemented using classes for the node and linked list objects.
This document discusses lists as an abstract data type (ADT) and their implementation using arrays and linked lists. It defines a list as a finite, ordered sequence of elements and describes common list operations like insertion, deletion, traversal etc. Linked lists are introduced as an alternative implementation where each node contains a data field and link to the next node. The advantages of linked lists over arrays for dynamic data are also highlighted. Various real-world applications of lists are listed like implementing stacks, queues, graphs and dynamic memory allocation.
There are a couple of new methods that you will be writing for this pr.pdfaamousnowov
There are a couple of new methods that you will be writing for this project. Some are easy, some
are hard. I have provided code that tests most of the methods by calling them from the main
method in the file ListTest.java. The test file will only work when you have done all the
methods. In COMP182LinkedList.java I have provided the signature (definition and input
parameters) for these methods. At this point to make sure you can run the file
(COMP182LinkedList.java that you downloaded from Cavas) I have added template values as
return types of the methods. For example, if the method returns an int then I added return 0 as the
return value. Here are the methods are as follows: Anything getFixst () Anything getLast () void
add (Anything value) void addafter (1nt index, Anyehtng value) Anything set(int index,
Rnything aewvalue) void removeAl1 (Anything vaiue) lastIndex (Anything value)
COMP182IinkedIi ateAnything; elone boolean equala (object in) CoMP182IinkedList
KAnythang? gplat () boolean hascycle () Node reveraeliat () Node oddeventiat () Node
deleteDuplicates () boolean ispalindrome () "For the last two methods, you need to add proper
testing to ListTest Java Method Specifications Here are more details for implementing each of
these methods. You need to complete all the following methods in the COMP182LinkedList
class. You can write the methods in any order you wish, but I suggest you do them in the order
they are listed. In particular, make sure all your methods work for empty lists, lists of different
sizes, etc as you can see from the sample test cases provided in ListTest.java. While grading your
project, we will make changes to these values! Also, make sure that your solutions do not modify
the original lists (unless you are specifically instructed to do so). roid main(String[] args) You
can use this method in the ListTest class to create lists as needed and test each of the methods
listed above. I have provided a few test cases, but you may want to add more to some of the
method tests. Until you get add working, you will need to use addFirst to create lists to test your
other methods. Anything getFirsto This method returns the value stored in the first node an the
list. It should prit an error message and seturn null if the list is empty. Anything getLasto This
method returns the value stored in the last node in the list. It should print an error mesiage and
retuin noll if the list is emipty. void add(Anything value) Thus method adds a nade containing
new yalue to the end of the last. This method returns the value stored in the first node in the list.
It should print an error message and return null if the list is empty. Anything getLast0 This
method returns the value stored in the last node in the list. It should print an error message and
retum null if the list is empty: void add(Anything value) This method adds a node containing
new value to the end of the list. void addAfter(int index, Anything value) This method adds a
node contai.
This document discusses different data structures. It begins by defining a data structure as an organization of data in different ways. It then classifies common data structures as arrays, linked lists, stacks, queues, trees and graphs. It provides definitions and examples of algorithms, arrays, and linked lists. It also includes algorithms for operations on arrays and linked lists like insertion, deletion and traversal. Finally, it discusses implementation of singly and doubly linked lists as stacks and deletion operations in linked lists.
This document provides an overview of a course on data structures and applications. The course covers fundamental data structures like arrays, stacks, queues, linked lists, trees, graphs, and hashing. It aims to teach how to represent data structures linearly, design solutions to problems using various data structures, and apply hashing techniques. The modules cover introduction to data structures and arrays, stacks and queues, linked lists, trees, and graphs and hashing.
This document defines and compares common data structures like lists, stacks, and queues. It describes their abstract definitions, common operations, and different implementation methods. Lists can be implemented with arrays or linked nodes and support insertion, deletion, and retrieval of elements. Stacks and queues follow last-in first-out and first-in first-out rules respectively.
This document discusses linear data structures like stacks and queues. It defines them as ordered data collections where items are added and removed from specific ends. Stacks follow LIFO while queues follow FIFO. The key operations for stacks are push and pop, while queues use enqueue and dequeue. Python implementations are shown using lists. Functions are created to add, remove, and display items for both stacks and queues.
This chapter discusses searching and sorting algorithms for arrays and strings. It covers sequential search, binary search, bubble sort, selection sort, and insertion sort. It also discusses using the Vector class to implement dynamic arrays and provides examples of searching voter data and converting strings to pig latin.
The document discusses stacks and queues as data structures. Stacks follow LIFO (Last In First Out) and allow insertion and deletion from one end only. Queues follow FIFO (First In First Out) and allow insertion from one end and deletion from the other. Both can be implemented using arrays or linked lists. Common operations on stacks are push and pop, while common operations on queues are insert and delete.
The document discusses stacks and queues as data structures. Stacks follow LIFO (Last In First Out) and involve push and pop operations on an array or linked list. Queues follow FIFO (First In First Out) and involve insert and delete operations, with insertion at the rear and deletion at the front. The document provides examples of implementing stacks and queues using arrays and linked lists, and describes the basic operations like creation, insertion, deletion, checking for empty/full.
–PLS write program in c++ thanxLinked List Sorting and Reversing.pdfpoblettesedanoree498
–PLS write program in c++ thanx
Linked List Sorting and Reversing
Write a C++ using your own linked list class to manage a list of string elements. Besides the
basic operations expected of a linked list (add an element, remove an element, check for empty
list, report size (number) of elements in the list, and print out the content of the list), the linked
list class also needs to have a method called sort() and a method called reverse() the manipulate
the string elements. The sort method rearranges the elements in the list so they are sorted in
alphabetical order. The reverse method reverses the order of the elements of the list. Do NOT use
recursion to implement either of these operations. pls write program in c++ thanx
Solution
#include
#include
using namespace std;
class Node{ //class node
public:
string data;
Node* next;
void SetData(string aData) { data = aData; };
void SetNext(Node* aNext) { next = aNext; };
};
class List{ //class list
Node *head;
public:
List() { head = NULL; };
void addElement(string data);
void removeElement(string data);
int isEmpty(Node* temp);
int size();
void print();
void sort();
void reverse();
};
int List::isEmpty(Node* temp){ //method to check whether list is empty or not
if(temp!=NULL)
return 1;
else
return 0;
}
void List::addElement(string data){ //method to add
Node* newNode=new Node();
newNode->SetData(data);
newNode->SetNext(NULL);
Node* temp=head;
if(temp!=NULL)
{
while(temp->next!=NULL)
{temp=temp->next;}
temp->next=newNode;
}
else
head=newNode;
}
void List::removeElement(string data){ //method for delete
Node* temp=head;
Node *prev=head;
if(isEmpty(temp)==1)
{//prev=temp;
while(temp!=NULL)
{
if(temp->data==data)
{prev->next=temp->next;
temp->next=NULL;
}
else
{prev=temp;
temp=temp->next;
}
}
}
else
cout<<\"Nothing to delete as linked list is empty \"<next;
}
}
return count;
}
void List::print(){ //method for print
Node* temp=head;
if(isEmpty(temp)==1){
while(temp!=NULL)
{
cout<data<<\" \";
temp=temp->next;
}
}
}
int main()
{
List list;
list.addElement(\"anshu\");
list.addElement(\"anurag\");
list.addElement(\"how\");
list.addElement(\"are\");
list.addElement(\"you?\");
int count=list.size();
cout<<\"size of the linked list= \"<.
C++ CodeConsider the LinkedList class and the Node class that we s.pdfarmyshoes
C++ Code
Consider the LinkedList class and the Node class that we saw in lecture. The LinkedList class
basically represents a singly linked list.
Now, for this lab, consider a doubly linked list, i.e. each node has a next and previous pointers to
the next and previous node, respectively.
Modify the Node class to reflect this change and implement the following methods for
DoublyLinkedList class:
addFirst
addLast
addAtIndex
removeFirst
removeLast
removeAtIndex
Note: We saw how to implement these methods for a singly linked list and the code is added as
an attachment.
C++ Code
*****************************************************************************
******************
*****************************************************************************
******************
C++ Code
Solution
#include
#include
using namespace std;
template
class Node
{
public:
T element; // Element contained in the node
Node *next; // Pointer to the next node
Node *previous;
Node(T element) // Constructor
{
this->element = element;
next = NULL;
}
};
template
class LinkedList
{
public:
LinkedList();
void addFirst(T element);
void addLast(T element);
T removeFirst() ;
T removeLast();
void addAtIndex(int index, T element);
T removeAtIndex(int index);
void traverseList();
private:
Node *head;
Node *tail;
int size;
};
template
LinkedList::LinkedList()
{
head = NULL;
tail = NULL;
size = 0;
}
template
void LinkedList::addFirst(T element)
{
Node *newNode = new Node(element);
newNode->next = head;
if(head != NULL) {
head->previous = newNode;
}
newNode->previous = NULL;
head = newNode;
size++;
if (tail == NULL)
tail = head;
}
template
void LinkedList::addLast(T element)
{
if (tail == NULL)
{
head = tail = new Node(element);
}
else {
tail->next = new Node(element);
tail = tail->next;
}
size++;
}
template
void LinkedList::addAtIndex(int index, T element)
{
if (index == 0)
addFirst(element);
else if (index >= size)
addLast(element);
else
{
Node *current = head;
for (int i = 1; i < index; i++)
current = current->next;
Node *temp = current->next;
current->next = new Node(element);
(current->next)->next = temp;
size++;
}
}
template
T LinkedList::removeFirst()
{
if (size == 0)
exit(1);
else
{
Node *temp = head;
head = head->next;
size--;
T element = temp->element;
delete temp;
return element;
}
}
template
T LinkedList::removeLast()
{
if (size == 0)
exit(1);
else if (size == 1)
{
Node *temp = head;
head = tail = NULL;
size = 0;
T element = temp->element;
delete temp;
return element;
}
else
{
Node *current = head;
for (int i = 0; i < size - 2; i++)
current = current->next;
Node *temp = tail;
tail = current;
tail->next = NULL;
size--;
T element = temp->element;
delete temp;
return element;
}
}
template
T LinkedList::removeAtIndex(int index)
{
if (index < 0 || index >= size)
exit(1);
else if (index == 0)
return removeFirst();
else if (index == size - 1)
return removeLast();
else {
Node *previous = head;
for (int i = 1; i < index; i++)
{
previous = previous->next;
}
Node *current = previous-.
This document outlines two assignments for a course on data structures and files. The first assignment involves implementing a stack using a linked list and using it for infix, postfix, and prefix notation conversions and evaluations. The second assignment involves implementing a priority queue using a linked list to service patients in a hospital based on priority of illness. Key algorithms for stack, queue, and priority queue operations are described.
Similar to Week 2 - Data Structures and Algorithms (20)
This document discusses blockchain and non-fungible tokens (NFTs). It provides examples of NFT use cases including digital art and assets. A case study of Bitscrunch, an NFT trading platform, is presented. Bitscrunch utilizes various technologies like AI and data analytics to provide services such as wash trade detection, price estimation, and portfolio tracking. NFT applications in education and the metaverse are also discussed. The talk concludes by emphasizing the growing role of virtual goods and digital ownership through NFTs.
Cloud AI is a machine learning platform used to create and deploy machine learning models in the cloud. It allows users to streamline workflows including data preparation, model training, evaluation and publishing models for use in other cloud services. The platform provides services like Machine Learning Studio for visual modeling, Data Science Workshop for interactive development, and Elastic Algorithm Service to deploy models as APIs.
This document is a slide presentation by Dr. Ferdin Joe John Joseph on cloud native computing for a class at the Faculty of Information Technology, Thai-Nichi Institute of Technology in Bangkok. The presentation covers cloud native concepts and applications over 41 slides, with the final slide indicating next week's topics will be on cloud AI and a demonstration.
This document appears to be a slide deck presentation on cloud security given by Dr. Ferdin Joe John Joseph from the Faculty of Information Technology at the Thai-Nichi Institute of Technology in Bangkok. Over 42 slides, it likely covered various topics relating to security in cloud computing such as access controls, encryption, identity management, auditing, and compliance. The presentation concluded by noting that next week's topic will be on cloud native technologies, Kubernetes, DevOps, and include a demonstration.
This document is a presentation on Relational Database Service (RDS) given by Dr. Ferdin Joe John Joseph from the Faculty of Information Technology at the Thai-Nichi Institute of Technology in Bangkok. The presentation introduces RDS as part of Alibaba Cloud's portfolio and provides a demonstration of its features and capabilities. It concludes by announcing that next week's topic will be on cloud security.
This document discusses a lecture on object storage services from Alibaba Cloud. It provides an overview of Alibaba Cloud's portfolio and a demonstration of the Object Storage Service (OSS). The presentation was given by Dr. Ferdin Joe John Joseph from the Faculty of Information Technology at the Thai-Nichi Institute of Technology in Bangkok. Next week's lecture will cover relational database services and include another demonstration.
Week 5: Elastic Compute Service (ECS) with Alibaba Cloud- DSA 441 Cloud Compu...Ferdin Joe John Joseph PhD
This document discusses a demonstration of Elastic Compute Service (ECS). It is presented by Dr. Ferdin Joe John Joseph from the Faculty of Information Technology at the Thai-Nichi Institute of Technology in Bangkok. The presentation covers ECS and is part of a cloud computing course. It provides an overview of ECS and previews that next week's topics will be autoscaling and server load balancing.
This document provides an introduction to cloud services, big data, and Hadoop. It discusses these topics delivered as part of a class on cloud computing. The presentation covers the Alibaba Cloud portfolio, Hadoop architecture including HDFS, and Alibaba Cloud big data products. It concludes by outlining that next week's class will cover Elastic Compute Service and include a demonstration.
Week 3: Virtual Private Cloud, On Premise, IaaS, PaaS, SaaS - DSA 441 Cloud C...Ferdin Joe John Joseph PhD
This document summarizes a lecture on virtual private clouds, on-premise infrastructure versus cloud infrastructure models (IaaS, PaaS, SaaS), and the key differences between them. It discusses what a virtual private cloud (VPC) is, how it uses virtual switches (vSwitches) to connect resources, and some of its features. It then compares on-premise systems with the various cloud models in terms of control, scalability, costs and other factors. For each cloud model (IaaS, PaaS, SaaS), it provides definitions, architectural diagrams, benefits and examples. Lastly, it outlines some criteria to consider when choosing between the different cloud models.
Virtualization allows multiple virtual machines to run on a single physical server, improving resource utilization. It provides benefits like partitioning resources between VMs, portability by saving VMs as files, and security through hardware isolation. A hypervisor manages virtual resources and presents virtual machines to guest operating systems, allowing virtualization of CPUs, storage, and networks. Common hypervisors include VMware ESXi, Hyper-V, KVM, and Xen, which run directly on hardware or on a host operating system.
This document outlines the syllabus for a 15-week cloud computing course. The course covers topics such as virtual machines, virtual private clouds, cloud services, elastic compute service, auto scaling, object storage, relational data service, cloud security, Kubernetes, and cloud platforms for AI. Students will complete assignments, a midterm exam, final exam, and capstone project. Assessment is based on attendance, midterm exam, assignments/project, and final exam.
The document outlines the program educational objectives, program outcomes, curriculum, and regulations for the B.Tech Artificial Intelligence and Data Science program at Anna University in Chennai, India. The 4-year program aims to provide students with proficiency in basic sciences, mathematics, AI, data science, and statistics to build data-driven systems. Students will develop technical skills to conduct research in AI and data science and create sustainable solutions. The curriculum covers topics such as data structures, algorithms, machine learning, deep learning, data analytics, and artificial intelligence across 8 semesters with theory, laboratory, and project components.
The document summarizes a technical talk given by Dr. Ferdin Joe John Joseph about Hadoop in Alibaba Cloud. The talk covered an introduction to big data and Hadoop, Hadoop architecture including its distributed file system HDFS, and Alibaba Cloud's big data products. It was presented at Loyola ICAM College of Engineering and Technology in Chennai, India on May 28, 2021.
The document provides an overview of cloud computing essentials from Alibaba Cloud. It defines cloud computing according to NIST as enabling on-demand access to a shared pool of configurable computing resources. The speaker then discusses key cloud properties like scalability, availability, and fault tolerance. The presentation also provides details on Alibaba Cloud's global infrastructure and popular products like Elastic Compute Service, Server Load Balancing, Auto Scaling, and Object Storage Service. It concludes with information on cloud certification opportunities from Alibaba Cloud.
This keynote talk discusses how computer vision is transforming from traditional convolutional neural networks (CNNs) to vision transformers (ViTs). ViTs break images down into patches that are fed into a transformer encoder, similar to how text is handled with word embeddings. This approach performs competitively with CNNs while being conceptually simpler. The talk outlines the architecture of ViTs and how they function, noting they ignore convolutions and analyze variants' significance. It encourages attendees to start exploring ViTs through an online tutorial and contacts the speaker for additional help.
The document discusses binary classification techniques including Naive Bayes classifiers and support vector machines (SVM). It explains that Naive Bayes classifiers use Bayes' theorem to calculate conditional probabilities for classification. Specifically, it describes how to calculate priors and fit probability distributions like binomial, multinomial, and Gaussian distributions for the Naive Bayes model. The document also outlines how SVMs find the optimal separating hyperplane between two classes by maximizing the margin between them. It provides code examples for implementing Naive Bayes and SVM classifiers and evaluating their performance.
This document summarizes a lesson on logistic regression for data analysis. It discusses logistic regression as a machine learning classification algorithm used to predict categorical dependent variables. It then describes assumptions of logistic regression, provides examples of its practical use, and outlines the steps taken in building a logistic regression model for a direct marketing dataset, including data preprocessing, model training and evaluation.
This document discusses different types of linear regression models including simple, multiple, and polynomial linear regression. It provides code examples for implementing linear regression using scikit-learn and statsmodels. Key steps covered include importing packages, providing data, creating and fitting regression models, obtaining results like coefficients and metrics, making predictions on new data, and visualizing models. Types of linear regression covered are simple linear regression with one variable, multiple linear regression with two or more variables, and polynomial regression with higher degree polynomials.
This document discusses feature engineering techniques for data analysis. It covers feature selection, construction, and engineering. Specific techniques discussed include feature imputation, handling outliers, binning, log transforms, one-hot encoding, grouping, splitting, scaling, and extracting date features. The document provides examples and explanations of these techniques to transform raw data into more useful features for machine learning models.
Codeless Generative AI Pipelines
(GenAI with Milvus)
https://ml.dssconf.pl/user.html#!/lecture/DSSML24-041a/rate
Discover the potential of real-time streaming in the context of GenAI as we delve into the intricacies of Apache NiFi and its capabilities. Learn how this tool can significantly simplify the data engineering workflow for GenAI applications, allowing you to focus on the creative aspects rather than the technical complexities. I will guide you through practical examples and use cases, showing the impact of automation on prompt building. From data ingestion to transformation and delivery, witness how Apache NiFi streamlines the entire pipeline, ensuring a smooth and hassle-free experience.
Timothy Spann
https://www.youtube.com/@FLaNK-Stack
https://medium.com/@tspann
https://www.datainmotion.dev/
milvus, unstructured data, vector database, zilliz, cloud, vectors, python, deep learning, generative ai, genai, nifi, kafka, flink, streaming, iot, edge
The Ipsos - AI - Monitor 2024 Report.pdfSocial Samosa
According to Ipsos AI Monitor's 2024 report, 65% Indians said that products and services using AI have profoundly changed their daily life in the past 3-5 years.
Predictably Improve Your B2B Tech Company's Performance by Leveraging DataKiwi Creative
Harness the power of AI-backed reports, benchmarking and data analysis to predict trends and detect anomalies in your marketing efforts.
Peter Caputa, CEO at Databox, reveals how you can discover the strategies and tools to increase your growth rate (and margins!).
From metrics to track to data habits to pick up, enhance your reporting for powerful insights to improve your B2B tech company's marketing.
- - -
This is the webinar recording from the June 2024 HubSpot User Group (HUG) for B2B Technology USA.
Watch the video recording at https://youtu.be/5vjwGfPN9lw
Sign up for future HUG events at https://events.hubspot.com/b2b-technology-usa/
ViewShift: Hassle-free Dynamic Policy Enforcement for Every Data LakeWalaa Eldin Moustafa
Dynamic policy enforcement is becoming an increasingly important topic in today’s world where data privacy and compliance is a top priority for companies, individuals, and regulators alike. In these slides, we discuss how LinkedIn implements a powerful dynamic policy enforcement engine, called ViewShift, and integrates it within its data lake. We show the query engine architecture and how catalog implementations can automatically route table resolutions to compliance-enforcing SQL views. Such views have a set of very interesting properties: (1) They are auto-generated from declarative data annotations. (2) They respect user-level consent and preferences (3) They are context-aware, encoding a different set of transformations for different use cases (4) They are portable; while the SQL logic is only implemented in one SQL dialect, it is accessible in all engines.
#SQL #Views #Privacy #Compliance #DataLake
1. Data Structures and
Algorithms
Week 2: Linked Lists
Ferdin Joe John Joseph, PhD
Faculty of Information Technology
Thai-Nichi Institute of Technology, Bangkok
2. Week 2
• Linked Lists
• Doubly Linked Lists
• Circular Linked Lists
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
2
3. Linked node question
• Suppose we have a long chain of list nodes:
• We don't know exactly how long the chain is.
• How would we print the data values in all the
nodes?
data next
10
data next
990
list ...data next
20
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
3
4. Algorithm pseudocode
Start at the front of the list.
While (there are more nodes to print):
Print the current node's data.
Go to the next node.
How do we walk through the nodes of the list?
list = list.next;//is this a good idea?
data next
10
data next
990
list
...
data next
20
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
4
5. Traversing a list?
• One (bad) way to print every value in the list:
while (list != null) {
System.out.println(list.data);
list = list.next;//move to next node
}
• What's wrong with this approach?
• (It loses the linked list as it prints it!)
data next
10
data next
990
list
...
data next
20
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
5
6. A current reference
• Don't change list. Make another variable, and
change it.
• A ListNode variable is NOT a ListNode object
ListNode current = list;
• What happens to the picture above when we write:
current = current.next;
data next
10
data next
990
list
...
data next
20
current
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
6
7. Traversing a list correctly
• The correct way to print every value in the list:
ListNode current = list;
while (current != null) {
System.out.println(current.data);
current = current.next; // move to
next node
}
• Changing current does not damage the list.
data next
10
data next
990
list
...
data next
20
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
7
8. Linked List vs. Array
• Print list values:
ListNode list= ...;
ListNode current = list;
while (current != null) {
System.out.println(current.data
);
current = current.next;
}
• Similar to array code:
int[] a = ...;
int i = 0;
while (i < a.length) {
System.out.println(a[i]);
i++;
}
Description Array Code Linked List Code
Go to front of list int i = 0; ListNode current = list;
Test for more elements i < size current != null
Current value elementData[i] current.data
Go to next element i++; current = current.next;
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
8
9. A LinkedIntList class
• Let's write a collection class named
LinkedIntList.
• Has the same methods as ArrayIntList:
• add, add, get, indexOf, remove, size, toString
• The list is internally implemented as a chain of linked
nodes
• The LinkedIntList keeps a reference to its front as a
field
• null is the end of the list; a null front signifies an empty list
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
9
10. LinkedIntList class v1
public class LinkedIntList {
private ListNode front;
public LinkedIntList() {
front = null;
}
methods go here
}
front =
LinkedIntList
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
10
11. Basic Structure
import java.io.*;
import java.util.LinkedList;
public class LinkedListDemo {
public static void main(String args[])
{
// Creating an empty LinkedList
LinkedList<String> list = new LinkedList<String>();
}
}
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
11
12. Implementing add
// Adds the given value to the end of
the list.
public void add(int value) {
...
}
• How do we add a new node to the end of a list?
• Does it matter what the list's contents are before the
add?
front =
data next
42
data next
-3
data next
17
element 0 element 1 element 2
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
12
13. Adding to an empty list
• Before adding 20: After:
• We must create a new node and attach it to the list.
front = front =
data next
20
element 0
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
13
14. The add method, 1st try
// Adds the given value to the end of
the list.
public void add(int value) {
if (front == null) {
// adding to an empty list
front = new ListNode(value);
} else {
// adding to the end of an
existing list
...
}
}
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
14
15. Adding to non-empty list
• Before adding value 20 to end of list:
• After:
front =
data next
42
data next
-3
front =
data next
42
data next
-3
data next
20
element 0 element 1 element 2
element 0 element 1
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
15
16. Don't fall off the edge!
• To add/remove from a list, you must modify the next
reference of the node before the place you want to
change.
• Where should current be pointing, to add 20 at the end?
• What loop test will stop us at this place in the list?
front =
data next
42
data next
-3
element 0 element 1
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
16
17. The add method
// Adds the given value to the end of the
list.
public void add(int value) {
if (front == null) {
// adding to an empty list
front = new ListNode(value);
} else {
// adding to the end of an existing
list
ListNode current = front;
while (current.next != null) {
current = current.next;
}
current.next = new ListNode(value);
}
}
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
17
18. Implementing get
// Returns value in list at given
index.
public int get(int index) {
...
}
• Exercise: Implement the get method.
front =
data next
42
data next
-3
data next
17
element 0 element 1 element 2
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
18
19. The get method
// Returns value in list at given
index.
// Precondition: 0 <= index < size()
public int get(int index) {
ListNode current = front;
for (int i = 0; i < index; i++) {
current = current.next;
}
return current.data;
}
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
19
20. Implementing add
// Inserts the given value at the given
index.
public void add(int index, int value) {
...
}
• Exercise: Implement the two-parameter add method.
front =
data next
42
data next
-3
data next
17
element 0 element 1 element 2
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
20
21. The add method
// Inserts the given value at the given index.
// Precondition: 0 <= index <= size()
public void add(int index, int value) {
if (index == 0) {
// adding to an empty list
front = new ListNode(value, front);
} else {
// inserting into an existing list
ListNode current = front;
for (int i = 0; i < index - 1; i++) {
current = current.next;
}
current.next = new ListNode(value,
current.next);
}
}
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
21
22. Implementing remove
// Removes the value at the given
index.
public void remove(int index, int
value) {
...
}
• Exercise: Implement the two-parameter add method.
front =
data next
42
data next
-3
data next
17
element 0 element 1 element 2
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
22
23. The remove method
LinkedList<String> list = new LinkedList<String>();
// Use add() method to add elements in the list
list.add("Geeks");
list.add("for");
list.add("Geeks");
list.add("10");
list.add("20");
// Output the list
System.out.println("LinkedList:" + list);
// Remove the head using remove()
list.remove("Geeks");
list.remove("20");
// Print the final list
System.out.println("Final LinkedList:" + list);
Output
LinkedList:[Geeks, for, Geeks, 10, 20]
Final LinkedList:[for, Geeks, 10]
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
23
24. Sample code
Implementation using Java
https://beginnersbook.com/2013/12/linkedlist-in-
java-with-example/
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
24
25. Week 2
• Linked Lists
• Doubly Linked Lists
• Circular Linked Lists
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
25
26. Doubly Linked List
Recall that the deletion of an element at the tail is not easy because we
have to find the node before the tail (the last node) by link hopping.
head
next
element
next nextnext
element element element
Baltimore Rome Seattle Toronto
tail
This problem can be easily solved by using the double linked list.
- Ed. 2 and 3.: Chapter 4
- Ed. 4: Chapter 3
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
26
27. A node in a doubly linked list: A compound object that
stores a reference to an element and two references, called
next and prev, to the next and previous nodes, respectively.
Reference to
next node
Reference to an
element
next
Element
Node
Reference to
previous node
prev
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
27
28. For convenience, a doubly linked list has a header node and a
trailer node. They are also called sentinel nodes, indicating
both the ends of a list.
header
Baltimore Rome Seattle
trailer
Difference from singly linked lists:
- each node contains two links.
- two extra nodes: header and trailer, which contain no
elements.
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
28
29. Class DLNode
Here is an implementation of nodes for doubly
linked lists in Java:
public class DLNode {
private Object element;
private DLNode next, prev;
public DLNode() {
this( null, null, null );
}
public DLNode( Object e, DLNode p, DLNode n
) {
element = e;
next = n;
prev = p;
}
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
29
30. void setElement( Object newElem ) {
element = newElem;
}
void setNext( DLNode newNext ) {
next = newNext;
}
void setPrev( DLNode newPrev ) {
prev = newPrev;
}
Object getElement() {
return element;
}
DLNode getNext() {
return next;
}
DLNode getPrev() {
return prev;
}
}
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
30
31. Insertion of an Element at the
Head
Before the insertion:
header
Baltimore Rome Seattle
trailer
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
31
32. DLNode x = new DLNode();
x.setElement(new String(“Toronto”));
(x.element = new String(“Toronto”))
Have a new node:
header
Rome Seattle
trailer
Baltimore
Toronto
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
32
34. After the insertion:
header
Rome Seattle
trailer
BaltimoreToronto
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
34
35. Deleting an Element at the Tail
Before the deletion:
header
Rome Seattle
trailer
BaltimoreToronto
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
35
38. Week 2
• Linked Lists
• Doubly Linked Lists
• Circular Linked Lists
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
38
39. Circular Linked List
• Last node references the first node
• Every node has a successor
Lecture series for Data Structures and
Algorithms, Data Science and Analytics, Thai-
Nichi Institute of Technology
39
40. Circular Linked List
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
40
41. Dummy Head Nodes
• Dummy head node
• Always present, even when the linked list is empty
• Insertion and deletion algorithms initialize prev to
reference the dummy head node, rather than null
Lecture series for Data Structures and
Algorithms, Data Science and Analytics, Thai-
Nichi Institute of Technology
41
42. Applications
Applications of linked list in computer science
Implementation of stacks and queues
Implementation of graphs : Adjacency list representation of graphs is most popular which is uses linked
list to store adjacent vertices.
Dynamic memory allocation : We use linked list of free blocks.
Maintaining directory of names
Performing arithmetic operations on long integers
Manipulation of polynomials by storing constants in the node of linked list representing sparse matrices
Applications of linked list in real world
Image viewer – Previous and next images are linked, hence can be accessed by next and previous
button.
Previous and next page in web browser – We can access previous and next url searched in web
browser by pressing back and next button since, they are linked as linked list.
Music Player – Songs in music player are linked to previous and next song. you can play songs
either from starting or ending of the list.
Lecture series for Data Structures and
Algorithms, Data Science and Analytics, Thai-
Nichi Institute of Technology
42
43. Next Week
Stack
Queue
Implementation in Java
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
43