The document discusses various linear data structures like arrays, strings, stacks, queues, and linked lists. It provides details on representing single and multi-dimensional arrays, including addressing formulas. Operations on ordered lists like lists are defined. Linear lists using arrays are implemented with methods for adding, removing, and changing elements.
The document discusses various concepts related to arrays in C/C++ including:
- What an array is and its key properties like contiguous memory locations and common data type
- Different types of arrays like single dimensional and multi dimensional
- How to declare, initialize and access array elements
- Passing arrays to functions
- Searching and sorting arrays
- Common array operations like insertion and deletion
The document discusses implementing a sorted linked list data structure in C++. It describes how to insert a new node into the linked list in the correct sorted position by finding the previous and current nodes between which the new node should be inserted. The key steps are to create a new node, find the previous and current nodes using a while loop, and connect the new node by updating the next pointers of the previous and current nodes.
This document provides information on arrays in Java. It begins by defining an array as a collection of similar data types that can store values of a homogeneous type. Arrays must specify their size at declaration and use zero-based indexing. The document then discusses single dimensional arrays, how to declare and initialize them, and how to set and access array elements. It also covers multi-dimensional arrays, providing syntax for declaration and initialization. Examples are given for creating, initializing, accessing, and printing array elements. The document concludes with examples of searching arrays and performing operations on two-dimensional arrays like matrix addition and multiplication.
DATA STRUCTURE CLASS 12 COMPUTER SCIENCEDev Chauhan
Arrays, stacks, queues, and linked lists are common data structures in computer science. Arrays allow direct access to elements but have fixed size, while linked lists can dynamically grow and shrink but require traversing nodes sequentially. Stacks follow LIFO (last in first out) and queues follow FIFO (first in first out) ordering for inserting and removing elements. Linked lists store data in nodes that link to the next node, allowing efficient insertion/removal anywhere in the list. Common operations on these structures include push/pop for stacks, enqueue/dequeue for queues, and insert/delete nodes for linked lists.
Arrays allow the storage and manipulation of multiple values of the same type. An array stores elements of the same type in a contiguous block of memory with indexes to access each element. One-dimensional arrays are declared with a size and accessed using indexes. Two-dimensional arrays represent tabular data and are accessed using row and column indexes. Arrays of objects allow storing and accessing multiple objects, and their elements can be accessed and manipulated similarly to primitive arrays.
Revisiting a data structures in detail with linked list stack and queuessuser7319f8
This document discusses various data structures including arrays, stacks, queues, and linked lists. It provides code examples for creating and manipulating each type of data structure. Specifically, it shows code for inserting and deleting elements from arrays and linked lists. It also includes algorithms and code for common stack and queue operations like push, pop, enqueue, and dequeue. The document provides a detailed overview of linear and non-linear data structures.
The document discusses various linear data structures like arrays, strings, stacks, queues, and linked lists. It provides details on representing single and multi-dimensional arrays, including addressing formulas. Operations on ordered lists like lists are defined. Linear lists using arrays are implemented with methods for adding, removing, and changing elements.
The document discusses various concepts related to arrays in C/C++ including:
- What an array is and its key properties like contiguous memory locations and common data type
- Different types of arrays like single dimensional and multi dimensional
- How to declare, initialize and access array elements
- Passing arrays to functions
- Searching and sorting arrays
- Common array operations like insertion and deletion
The document discusses implementing a sorted linked list data structure in C++. It describes how to insert a new node into the linked list in the correct sorted position by finding the previous and current nodes between which the new node should be inserted. The key steps are to create a new node, find the previous and current nodes using a while loop, and connect the new node by updating the next pointers of the previous and current nodes.
This document provides information on arrays in Java. It begins by defining an array as a collection of similar data types that can store values of a homogeneous type. Arrays must specify their size at declaration and use zero-based indexing. The document then discusses single dimensional arrays, how to declare and initialize them, and how to set and access array elements. It also covers multi-dimensional arrays, providing syntax for declaration and initialization. Examples are given for creating, initializing, accessing, and printing array elements. The document concludes with examples of searching arrays and performing operations on two-dimensional arrays like matrix addition and multiplication.
DATA STRUCTURE CLASS 12 COMPUTER SCIENCEDev Chauhan
Arrays, stacks, queues, and linked lists are common data structures in computer science. Arrays allow direct access to elements but have fixed size, while linked lists can dynamically grow and shrink but require traversing nodes sequentially. Stacks follow LIFO (last in first out) and queues follow FIFO (first in first out) ordering for inserting and removing elements. Linked lists store data in nodes that link to the next node, allowing efficient insertion/removal anywhere in the list. Common operations on these structures include push/pop for stacks, enqueue/dequeue for queues, and insert/delete nodes for linked lists.
Arrays allow the storage and manipulation of multiple values of the same type. An array stores elements of the same type in a contiguous block of memory with indexes to access each element. One-dimensional arrays are declared with a size and accessed using indexes. Two-dimensional arrays represent tabular data and are accessed using row and column indexes. Arrays of objects allow storing and accessing multiple objects, and their elements can be accessed and manipulated similarly to primitive arrays.
Revisiting a data structures in detail with linked list stack and queuessuser7319f8
This document discusses various data structures including arrays, stacks, queues, and linked lists. It provides code examples for creating and manipulating each type of data structure. Specifically, it shows code for inserting and deleting elements from arrays and linked lists. It also includes algorithms and code for common stack and queue operations like push, pop, enqueue, and dequeue. The document provides a detailed overview of linear and non-linear data structures.
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.
JAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdfarpaqindia
JAVA
LAB #8 - ARRAY BASED LISTS
The next exercise is based on this implemetation for an UnorderedArrayList of integers:
//Interface: ArrayListADT
//works for int
public interface ArrayListADT {
public boolean isEmpty(); //Method to determine whether the list is empty.
public boolean isFull(); //Method to determine whether the list is full.
public int listSize(); //Method to return the number of elements in the list.
public int maxListSize(); //Method to return the maximum size of the list.
public void print(); //Method to output the elements of the list.
public boolean isItemAtEqual(int location, int item); //Method to determine whether item is
the same as the item in the list at location.
public void insertAt(int location, int insertItem); //Method to insert insertItem in the list at
the position
public void insertEnd(int insertItem); //Method to insert insertItem at the end of the list.
public void removeAt(int location); //Method to remove the item from the list at location.
public int retrieveAt(int location); //Method to retrieve the element from the list at location.
public void replaceAt(int location, int repItem); //Method to replace the element in the list at
location with repItem.
public void clearList(); //Method to remove all the elements from the list.
public int search(int searchItem); //Method to determine whether searchItem is in the list.
public void remove(int removeItem); //Method to remove an item from the list.
}
//Class: ArrayListClass implements
//Interface: ArrayListADT
public abstract class ArrayListClass implements ArrayListADT {
protected int length; //to store the length of the list
protected int maxSize; //to store the maximum size of the list
protected int[] list; //array to hold the list elements
//Default constructor
public ArrayListClass() {
maxSize = 100;
length = 0;
list = new int[maxSize];
}
//Alternate Constructor
public ArrayListClass(int size) {
if(size <= 0) {
System.err.println(\"The array size must be positive. Creating an array of size 100.\");
maxSize = 100;
}
else
maxSize = size;
length = 0;
list = new int[maxSize];
}
public boolean isEmpty() {
return (length == 0);
}
public boolean isFull() {
return (length == maxSize);
}
public int listSize() {
return length;
}
public int maxListSize() {
return maxSize;
}
public void print() {
for (int i = 0; i < length; i++)
System.out.print(list[i] + \" \");
System.out.println();
}
public boolean isItemAtEqual(int location, int item) {
if (location < 0 || location >= length) {
System.err.println(\"The location of the item to be compared is out of range.\");
return false;
}
return list[location]== item;
}
public void clearList() {
for (int i = 0; i < length; i++)
list[i] = 0;
length = 0;
System.gc(); //invoke the Java garbage collector
}
public void removeAt(int location) {
if (location < 0 || location >= length)
System.err.println(\"The location of the item to be removed is out of range.\");
else {
for(int i = location; i < length - 1; i++)
list[i] = list[i + 1.
Lab_3- Objective- Experiment with Lists- Stacks- and Queues- Simulate.docxrennaknapp
Lab_3: Objective: Experiment with Lists, Stacks, and Queues: Simulate an OS task manager
Assignment:
Using the startup code, implement the following:
1-Create List L1 of 10 elements (task IDs), e.g. L1 = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10;
2-Insert a new list element in between (at every other element), such as: 1,100, 2,200, 3,300, 4,400, ... 10,1000;
Simulate a new CPU core assignment:
3-Create another List L2, and extract the newly inserted elements into this new list L2
i.e. L1 should go back to the original list: L1 = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
L2 should be: 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000
Start executing:
4-Create a Queue Q1 by extracting L1, and inserting L2 elements: i.e. Q should start with: 1,2,3, ... 10, and (10, 20 ... 100) will be inserted
Q1=1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000
Label tasks as finished with the possibility of revisiting a task, such as:
5-Create a Stack S1 which by deleting the elements of Q1 and inserting them in L1
6-Pop out all elements of the Stack, i.e. should end up with an empty stack
Extra credit: Simulate a re-executed task, i.e. Pop out a task out of the Stack and reinsert, this simulate a failed task.
7-Verify the functionality and capture the results in a report form.
List.h
main.cpp
#include "List.h"
#include <stdlib.h>
#include <iostream>
using namespace std;
template <typename Object>
class Stack
{
public:
bool isEmpty() const
{
return theList.empty();
}
const Object& top() const
{
return theList.front();
}
void push(const Object& x)
{
theList.push_front(x);
}
void pop(Object& x)
{
x = theList.front(); theList.pop_front();
}
private:
List<Object> theList;
};
template <typename Object>
class Queue
{
public:
bool isEmpty() const
{
return theList.empty();
}
const Object& getFront() const
{
return theList.front();
}
void enqueue(const Object& x)
{
theList.push_back(x);
}
void dequeue(Object& x)
{
x = theList.front(); theList.pop_front();
}
private:
List<Object> theList;
};
int main()
{
int i;
const int N = 10;
List<int> L1;
Stack<int> S1;
Queue<int> Q1;
List<int>::iterator node; //Variable to keep track of the position as we traverse
// List Section example:
//Q1: Create List L1 of 10 elements, e.g. L1 = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10;
// create the list array as a starting point:
for (i = N; i > 0; --i)
{
L1.push_front(i);
}
// show L1 with an iterator
cout << "List L1 is:" << endl;
for (auto it = L1.begin(); it != L1.end(); ++it)
{
cout << *it << ' ';
}
// Stack Section example:
//
// Stack to be created per the above assignment requirment
cout << "\nStack S1 is:" << endl;;
for (i = N - 1; i >= 0; --i)
{
S1.push(i);
cout << S1.top() << " " << endl;
}
while (!S1.isEmpty())
{
cout << S1.top() << endl;
S1.pop(i);
}
// Queue section, to be created per the above assignment requirment
//
//
return 0;
}
please answer with C++ code thank you!
private: int theSize; Node *head.
This document summarizes Chapter 2 on arrays and structures from a textbook on data structures in C. It outlines key topics like the array abstract data type, structures and unions, polynomial and sparse matrix abstract data types, multidimensional arrays, and strings. Examples are provided on implementing arrays, structures, polynomials, and various operations like addition and multiplication on polynomials.
This document summarizes Chapter 2 on arrays and structures from a textbook on data structures in C. It covers various abstract data types including arrays, polynomials, sparse matrices, and strings. It provides examples of implementing one-dimensional and multi-dimensional arrays in C. Structures and unions are described as a way to group heterogeneous data. Self-referential structures and implementation of abstract data types using arrays are also discussed.
2.(Sorted list array implementation)This sorted list ADT discussed .pdfarshin9
2.(Sorted list: array implementation)This sorted list ADT discussed in class should be extended
by the addition of two new methods:
//Interface: ArrayListADT
//works for int
public interface ArrayListADT {
public boolean isEmpty(); //Method to determine whether the list is empty.
public boolean isFull(); //Method to determine whether the list is full.
public int listSize(); //Method to return the number of elements in the list.
public int maxListSize(); //Method to return the maximum size of the list.
public void print(); //Method to output the elements of the list.
public boolean isItemAtEqual(int location, int item); //Method to determine whether item is
the same as the item in the list at location.
public void insertAt(int location, int insertItem); //Method to insert insertItem in the list at
the position
public void insertEnd(int insertItem); //Method to insert insertItem at the end of the list.
public void removeAt(int location); //Method to remove the item from the list at location.
public int retrieveAt(int location); //Method to retrieve the element from the list at location.
public void replaceAt(int location, int repItem); //Method to replace the element in the list at
location with repItem.
public void clearList(); //Method to remove all the elements from the list.
public int search(int searchItem); //Method to determine whether searchItem is in the list.
public void remove(int removeItem); //Method to remove an item from the list.
}
//Class: ArrayListClass implements
//Interface: ArrayListADT
public abstract class ArrayListClass implements ArrayListADT {
protected int length; //to store the length of the list
protected int maxSize; //to store the maximum size of the list
protected int[] list; //array to hold the list elements
//Default constructor
public ArrayListClass() {
maxSize = 100;
length = 0;
list = new int[maxSize];
}
//Alternate Constructor
public ArrayListClass(int size) {
if(size <= 0) {
System.err.println(\"The array size must be positive. Creating an array of size 100.\");
maxSize = 100;
}
else
maxSize = size;
length = 0;
list = new int[maxSize];
}
public boolean isEmpty() {
return (length == 0);
}
public boolean isFull() {
return (length == maxSize);
}
public int listSize() {
return length;
}
public int maxListSize() {
return maxSize;
}
public void print() {
for (int i = 0; i < length; i++)
System.out.print(list[i] + \" \");
System.out.println();
}
public boolean isItemAtEqual(int location, int item) {
if (location < 0 || location >= length) {
System.err.println(\"The location of the item to be compared is out of range.\");
return false;
}
return list[location]== item;
}
public void clearList() {
for (int i = 0; i < length; i++)
list[i] = 0;
length = 0;
System.gc(); //invoke the Java garbage collector
}
public void removeAt(int location) {
if (location < 0 || location >= length)
System.err.println(\"The location of the item to be removed is out of range.\");
else {
for(int i = location; i < length - 1; i++)
list[i] .
Design your own List ADT named StringList to provide the following .pdfprajeetjain
Design your own List ADT named StringList to provide the following operations on a list
object: 1. add (void add(String item) 2. remove (void remove(int index) and void
remove(String item)) 3. size() (int size()) 4. isEmpty (boolean isEmpty() ) 5. indexOf (int
indexOf(String item)) 6. hasItem (boolean hasItem(String item) ) 7. isFull (boolean isFull() ) 8.
getByIndex (String getByIndex(int index)) 9. toString (String toString(), which returns items in
the list in the format as specified below: [Bottle water, Turkey, Oil, Banana] You
are required to use array to implement this ADT. Array only, no other data structures can be used
to implement the structure.
Solution
public class ADT
{
String a[] = new String[1000];
int len=0;
void add(String s)//add item to array
{
a[len++]=s;
System.out.println(\"\ data added to array\ \");
}
void remove(String s)//remove item from array
{
int i,j;
i = indexOf(s);
if(i!=-1){
for(j=i;j.
ReversePoem.java ---------------------------------- public cl.pdfravikapoorindia
ReversePoem.java :-
---------------------------------
public class ReversePoem {
/*This programs has you display a pessimistic poem from a list of phrases*/
// and then reverse the phrases to find another more optimistic poem.
public static void main(String[] args) throws Exception
{
//Queue object
MyQueue queue = new MyQueue<>();
//Stack object
MyStack stack = new MyStack<>();
//String buffer to apppend all Strings
StringBuffer sb = new StringBuffer();
// Create a single String object from the 16 Strings below
String set1 = \"I am part of a lost generation#and I refuse to believe that#\";
sb.append(set1);
String set2 = \"I can change the world#I realize this may be a shock but#\";
sb.append(set2);
String set3 = \"\'Happiness comes from within\'#is a lie, and#\";
sb.append(set3);
String set4 = \"\'Money will make me happy\'#So in 30 years I will tell my children#\";
sb.append(set4);
String set5 = \"they are not the most important thing in my life#\";
sb.append(set5);
String set6 = \"My employer will know that#I have my priorities straight because#\";
sb.append(set6);
String set7 = \"work#is more important than#family#I tell you this#\";
sb.append(set7);
String set8 = \"Once upon a time#Families stayed together#\";
sb.append(set8);
String set9 = \"but this will not be true in my era#\";
sb.append(set9);
String set10 = \"This is a quick fix society#Experts tell me#\";
sb.append(set10);
String set11 = \"30 years from now, I will be celebrating the 10th anniversary of my
divorce#\";
sb.append(set11);
String set12 = \"I do not concede that#I will live in a country of my own making#\";
sb.append(set12);
String set13 = \"In the future#Environmental destruction will be the norm#\";
sb.append(set13);
String set14 = \"No longer can it be said that#My peers and I care about this earth#\";
sb.append(set14);
String set15 = \"It will be evident that#My generation is apathetic and lethargic#\";
sb.append(set15);
String set16 = \"It is foolish to presume that#There is hope#\";
sb.append(set16);
String finalString = sb.toString();
String itmes[] = finalString.split(\"#\");
System.out.println(\"========== Original Phrase ==============\");
for(int i = 0 ; i < itmes.length;i++){
queue.enqueue(itmes[i]);
System.out.println(itmes[i]);
}
for(int i = 0 ; i < itmes.length;i++){
stack.push(queue.dequeue());
}
System.out.println(\"========== Reverse Phrase ==============\");
for(int i = 0 ; i < itmes.length;i++){
System.out.println(stack.pop());
}
/* You are given a list of phrases in Strings; the phrases
are separated by pound signs: \'#\':
1. Create a single String object from this list.
2. Then, split the String of phrases into an array of
phrases using the String split method.
3. Display a poem by walking through the array and
displaying each phrase one per line.
4. And, at the same time, place each phrase on a
MyQueue object using only the enqueue method.
5. After all the phrases have been placed on the queue,
transfer the phrases from the MyQueue object to a
MyS.
This document describes the ArrayLinearList class, which implements a linear list using an array. It includes methods for creating empty lists, adding and removing elements, checking sizes, and converting the list to a string. The class uses an array to store elements, and resizes the array when needed to add elements. Methods are provided for common list operations like get, indexOf, and remove.
Refer to my progress on this assignment belowIn this problem you w.pdfarishmarketing21
Refer to my progress on this assignment below
In this problem you will make it “more” object-oriented in the following ways:
-You will change its name to SortedList
-You will change the constructor that takes no arguments to be more traditional and initialize the
member fields to dummy values.
-You will add a constructor that takes in an initialized array and a size
-You will add an insert function that adds a value to the list and maintains its sorted-ness
-You will add a quicksort function check the below code.
-You will make updates as necessary to the main function so that it still runs and tests your code.
The code below seems to sort correctly but it skips over some items in the array and I am not
sure what is happening. Please help! Thanks!
import java.util.Scanner;
class SortedList
{
private static int array[];
private static int n;
public SortedList()
{
Scanner in = new Scanner(System.in);
System.out.println(\"Enter number of elements\");
n = in.nextInt();
array = new int[n];
if(n == 0) {
System.out.print(\"Since no arguments array set to: \");
} else {
System.out.print(\"Creating array size \" + n + \": \");
}
for(int i = 0; i < n; i++)
{
array[i] = 0;
}
//System.out.println(\"Enter \" + n + \" integers in ascending order\");
/*for (c = 0; c < n; c++)
array[c] = in.nextInt();*/
for(int i = 0; i < n; i++)
{
System.out.print(array[i] + \" \");
}
System.out.print(\"\ \");
}
public SortedList(int a[], int size)
{
array = a;
n = size;
}
public int binsearch(int search)
{
int first, last, middle;
first = 0;
last = n - 1;
middle = (first + last)/2;
while( first <= last )
{
if ( array[middle] < search )
first = middle + 1;
else if ( array[middle] == search )
{
//System.out.println(search + \" found at location \" + (middle + 1) + \".\");
return middle+1;//+1 for the non-CS people who don\'t start counting at zero.
}
else
last = middle - 1;
middle = (first + last)/2;
}
return -1;
//System.out.println(search + \" is not present in the list.\ \");
}
public static int partition(int input[], int p, int r)
{
int pivot = input[r];
while(p < r)
{
while(input[p] < pivot)
{
p++;
}
while(input[r] > pivot)
{
r--;
}
if(input[p] == input[r])
{
p++;
}
else if(p < r)
{
int tmp = input[p];
input[p] = input[r];
input[r] = tmp;
}
}
return r;
}
public static void quicksort(int input[], int p, int r)
{
if(p < r)
{
int j = partition(input, p, r);
quicksort(input, p, j-1);
quicksort(input, j+1, r);
}
}
public static void insert(int value, int cell)
{
array[cell] = value;
quicksort(array, 0, n-1);
}
public static void main(String args[])
{
int c;
Scanner in = new Scanner(System.in);
SortedList b = new SortedList();
System.out.println(\"Input numbers\");
for(int i = 0; i < n; i++)
{
c = in.nextInt();
in.nextLine();
insert(c, i);
}
in.close();
for(int j = 0; j < n; j++)
{
System.out.print(array[j] + \", \");
}
}
}
Solution
//the whole program that you wrote is correct except one line , when you call the quicksort
everytime you insert a //value dont pass n pass the i.
This document provides information on arrays in C programming. It defines an array as a collection of data storage locations with the same name and data type. It discusses array declaration, initialization, accessing elements using indexes, insertion and deletion of elements, and multi-dimensional arrays. Code examples are provided to demonstrate printing the contents of 1D, 2D and 3D arrays. The document also lists some reference books for learning C programming.
Engineering lecture ppt by venay magenvenaymagen19
Venay Magen likes the shading red, particularly on Tuesdays. He cherishes to drink bourbon (on all days). He figured out how to drink whisky from his youth companion Zippo, when they went to class together at Mount Temple Comprehensive School. He is best known as the lead vocalist for the band MN3.
Labprogram.java
LinkedList.java
import java.util.NoSuchElementException;
public class LinkedList {
private class Node {
private T data;
private Node next;
private Node prev;
public Node(T data) {
this.data = data;
this.next = null;
this.prev = null;
}
}
private int length;
private Node first;
private Node last;
private Node iterator;
/**** CONSTRUCTORS ****/
public LinkedList() {
first = null;
last = null;
iterator = null;
length = 0;
}
/**
* Converts the given array into a LinkedList
*
* @param array the array of values to insert into this LinkedList
* @postcondition
*/
public LinkedList(T[] array) {
}
/**
* Instantiates a new LinkedList by copying another List
*
* @param original the LinkedList to copy
* @postcondition a new List object, which is an identical,
* but separate, copy of the LinkedList original
*/
public LinkedList(LinkedList original) {
}
public T getFirst() throws NoSuchElementException {
if (isEmpty()) {
throw new NoSuchElementException("The list is empty");
}
return first.data;
}
public T getLast() throws NoSuchElementException {
if (isEmpty()) {
throw new NoSuchElementException("The list is empty");
}
return last.data;
}
public T getIterator() throws NullPointerException {
if (iterator != null) {
return iterator.data;
} else {
throw new NullPointerException("Iterator is off the end opf the list.");
}
}
public int getLength() {
return length;
}
public boolean isEmpty() {
return length == 0;
}
public boolean offEnd() {
return iterator == null;
}
public void addFirst(T data) {
Node newNode = new Node(data);
if (isEmpty()) {
first = newNode;
last = newNode;
} else {
newNode.next = first;
first.prev = newNode;
first = newNode;
}
length++;
}
public void addLast(T data) {
Node newNode = new Node(data);
if (isEmpty()) {
first = newNode;
last = newNode;
} else {
last.next = newNode;
newNode.prev = last;
last = newNode;
}
length++;
}
public void addIterator(T data) throws NullPointerException {
if (offEnd()) {
throw new NullPointerException("addIterator Iterator is off end.");
}
if (iterator == last) {
addLast(data);
} else {
Node newNode = new Node(data);
Node next = iterator.next;
newNode.next = next;
newNode.prev = iterator;
iterator.next = newNode;
next.prev = newNode;
length++;
}
}
public void removeFirst() throws NoSuchElementException {
if (isEmpty()) {
throw new NoSuchElementException("The list is empty");
}
if (length == 1) {
first = null;
last = null;
iterator = null;
} else {
if (iterator == first) {
iterator = null;
}
first = first.next;
first.prev = null;
}
length--;
}
public void removeLast() throws NoSuchElementException {
if (isEmpty()) {
throw new NoSuchElementException("The list is empty");
}
if (length == 1) {
first = null;
last = null;
iterator = null;
} else {
if (iterator == last) {
iterator = null;
}
last = last.prev;
last.next = null;
}
length--;
}
public void removeIterator() throws NullPointerException {
if (offEnd()) {
throw new NullPointerException("Iterator is off the end opf the list.");
}
if (iterator .
This document discusses arrays in C++. It defines an array as a collection of the same type of data. Arrays can be initialized using a loop or by declaring and initializing in one step. Multidimensional arrays represent 2D data with rows and columns. Examples are provided to demonstrate reading from and printing to arrays, as well as searching, copying, and calculating averages of array elements.
I need help with this code working Create another project and add yo.pdffantoosh1
I need help with this code working Create another project and add your jar file in this project. In
the main method of App class of this second project test your MyArrayList class. It is mandatory
to follow the instructions to get full credit. You need to perform the following actions. 1. Create
five strings, A1",,'B2",,'C3",'D4",'E5" 2. Save these Strings in your MyArrayList 3. Print a
message "Displaying List" 4. Display the list 5. Insert another String in your MyArrayList at
location 2 6. Print a message "Inserting Item" 7. Display the list 8. Remove String at location 0 9.
Print a message "Removing Item" 10. Display the list 11. Print a message "Setting a String" 12.
Set a new String in location 1 13. Display the list 14. Check whether "D4" is present in the list or
not, print an appropriate message 15. Find the index of "E5" in your list, print an appropriate
message 16. Print a message "Emptying List" 17. Empty the list 18. Print the size of the list
These steps check most of your MyArrayList functionality. I will also perform my own checks of
your code while grading. Deliverable: a. Copy the utils.jar file in your project folder. b. Make a
zip file of full project, not the src folder only or java files only. c. Submit the zip file. Grading
Rubric: The project is not submitted as required: 0 points
st.java J MyArrayList.java 2 J App.java 2 J MyFile.java 2 rc >J MyArrayList.java >q&
MyArrayList > get(int) public class MyArrayList implements MyList \{ Object [] obj = new
Object [1]; int size; public int size()\{ return size; \} public object get(int index) if (index <0
index >= size ){// throw new indexo return obj [index]; \} return index; // this should be deleted
after public void add (Object 0 ) \{ //if this test fails there is a space in the array. // it will pass
itself. if ( size == obj. length ){ Object [] obj2 = new 0 bject [obj. length 2]; for(int i=0;i<0bj.
length; i++){ obj2[i]=obj [i] ; \} obj=obj2; \} obj [ size ]=0; size++; \} public void add(int index,
Object o) \{ if(index > size || index <0 ) \{ throw new IndexOut0fBoundsException(index); \} if
(size == obj. length ){ Object [] obj2 = new Object [obj. length 2 ]; for(int i=0;i<0bj. length;
i++){ obj 2[i]=obj[i]; \} obj=obj2; \} if (index i=size;i>= index; i){ nhi [i=nhii1 : Ln 16, Col 56
Spaces: 4 UTF-8 LF \{\} Java
In this lab you will add an interface to the MyUtils project, and implement it in your
MyArrayList class in the MyUtils project. You will test the newly added functionality of your
MyArrayList class in another project. The UML for the Interface is as follows S Description of
methods Following method are self-explanatory: size(), get(int index), add (object o), remove
(int index), and isEmpty). Below is the description of all other methods. void add(int index,
Object o) inserts the given reference of object o at location index, making all entries move down
a spot. void remove (Object o) removes the first occurrence of object o in the list, moving all
entries .
The document discusses stacks and their implementation and applications. Stacks are LIFO data structures that can be implemented using arrays. Key operations on stacks include push, pop, peek, isEmpty and isFull. Stacks have various applications including expression evaluation, recursion, function calls and memory management. Stacks can grow either upwards or downwards in the array.
The document discusses arrays in C programming. It defines key concepts like array representation, index starting from 0, memory representation of arrays, and address calculation of array elements. It also covers various array operations like creation, copying, deletion, insertion, sorting, and representation of arrays as abstract data types. Multidimensional arrays and their row-major and column-major representations are explained along with examples.
lab08/build.bat
@echo off
cls
set DRIVE_LETTER=%1:
set PATH=%DRIVE_LETTER%\MinGW\bin;%DRIVE_LETTER%\MinGW\msys\1.0\bin;%DRIVE_LETTER%\MinGW\gtkmm3\bin;%DRIVE_LETTER%\MinGW\gtk\bin;c:\Windows;c:\Windows\system32
set PROJECT_PATH=.
make DRIVE_LETTER="%DRIVE_LETTER%" PROJECT_DIR="%PROJECT_PATH%"
lab08/CSC2110/CD.h
#if !defined CD_H
#define CD_H
#include "Song.h"
#include "Text.h"
using CSC2110::String;
#include "ListArray.h"
using CSC2110::ListArray;
namespace CSC2110
{
class CD
{
private:
String* artist;
String* title;
int year;
int rating;
int num_tracks;
ListArray<Song>* songs;
public:
CD(String* artist, String* title, int year, int rating, int num_tracks);
virtual ~CD();
String* getKey();
void addSong(String* title, String* length);
void displayCD();
static ListArray<CD>* readCDs(const char* file_name);
static int compare_items(CD* one, CD* two);
static int compare_keys(String* sk, CD* cd);
static char getRadixChar(CD* cd, int index); //1-based
};
}
#endif
lab08/CSC2110/Double.h
#if !defined (DOUBLE_H)
#define DOUBLE_H
namespace CSC2110
{
class Double
{
private:
double value;
public:
Double(double val);
~Double();
double getValue();
};
}
#endif
lab08/CSC2110/HighPerformanceCounter.h
#if !defined (HIGHPERFORMANCECOUNTER_H)
#define HIGHPERFORMANCECOUNTER_H
namespace CSC2110
{
class HighPerformanceCounter
{
private:
double micro_spt; //micro_seconds per tick
HighPerformanceCounter();
static HighPerformanceCounter* hpc;
static int getTicksPerSecond();
public:
virtual ~HighPerformanceCounter();
static HighPerformanceCounter* getHighPerformanceCounter();
int getCurrentTimeInTicks();
double getTimeDifferenceInMicroSeconds(int start_time, int end_time);
};
}
#endif
lab08/CSC2110/Integer.h
#if !defined (INTEGER_H)
#define INTEGER_H
namespace CSC2110
{
class Integer
{
private:
int value;
public:
Integer(int val);
virtual ~Integer();
int getValue();
};
}
#endif
lab08/CSC2110/Keyboard.h
#if !defined KEYBOARD_H
#define KEYBOARD_H
#include "Text.h"
using CSC2110::String;
#include <string>
using namespace std;
namespace CSC2110
{
class Keyboard
{
private:
Keyboard();
public:
virtual ~Keyboard();
static Keyboard* getKeyboard();
//pre: the string (character literal) that will prompt the user for input
//post: the input read from the keyboard interpreted as an int is returned
int readInt(string prompt);
int getValidatedInt(string prompt, int min, int max);
//pre: the string that will prompt the user for input
//post: the input read from the keyboard interpreted as a double is returned
double readDouble(string prompt);
double getValidatedDouble(string prom ...
How do you stop infinite loop Because I believe that it is making a.pdffeelinggift
How do you stop infinite loop? Because I believe that it is making an infinite circular list.
c++ code:
Here is the list class:
#ifndef LIN_J_LIST
#define LIN_J_LIST
typedef unsigned int uint;
#include
#include
using namespace std;
/**
* a simplified generic singly linked list class to illustrate C++ concepts
* @author Jerry Lin
* @version 2/17/17
*/
template< typename Object >
class List
{
private:
/**
* A class to store data and provide a link to the next node in the list
*/
class Node
{
public:
/**
* The constructor
* @param data the data to be stored in this node
*/
explicit Node( const Object & data )
: data{ data }, next{ nullptr } {}
Object data;
Node * next;
};
public:
/**
* The constructor for an empty list
*/
List()
: size{ 0 }, first{ nullptr }, last{ nullptr } {}
/**
* the copy constructor-creates and copy the list
*/
List( List && rhs ) = delete;
List( const List & rhs )
{
count = 0;
size = 0;
if(rhs.size != 0)
{
push_front(rhs.front());
Node * current = rhs.first;
Node * tempNode = first;
size++;
while(current->next != nullptr)
{
current = current->next;
Node *newNode = new Node(current->data); //transfer the data. basic op.
count++;
tempNode->next = newNode;
last = newNode;
tempNode = tempNode->next;
size++;
}
}
// you document and implement this method
}
/**
* the operator= method-copies the list
*/
List & operator=( List && rhs) = delete;
List & operator=( const List & rhs )
{
count = 0;
size = 0;
if( size != 0 )
{
Node * current = first;
Node * temp;
while( current != nullptr )
{
temp = current;
current = current->next;
delete temp;
}
}
if(rhs.size!= 0)
{
push_front(rhs.front());
Node * current = rhs.first;
Node * tempNode = first; //create a temporary to store
size++;
while(current -> next != nullptr)
{
current = current->next;
Node *newNode = new Node(current->data); //transfer the data. basic op
count++;
tempNode->next = newNode;
last = newNode;
tempNode = tempNode -> next;
size++;
}
}
return *this;
// you document and implement this method
}
/**
* accessor
* @return count
*/
int get_count() const
{
return count;
}
/**
* The destructor that gets rid of everything that\'s in the list and
* resets it to empty. If the list is already empty, do nothing.
*/
~List()
{
if( size != 0 )
{
Node * current = first;
Node * temp;
while( current != nullptr )
{
temp = current;
current = current->next;
delete temp;
}
}
}
/**
* Put a new element onto the beginning of the list
* @param item the data the new element will contain
*/
void push_front( const Object& item )
{
Node * new_node = new Node( item );//basic op.
if(is_empty())
{
last = new_node;
}
else
{
new_node->next = first;
}
first = new_node;
size++;
/* you complete the rest */
}
/**
* Remove the element that\'s at the front of the list. Causes an
* assertion error if the list is empty.
*/
void pop_front()
{
assert( !is_empty() );
Node * temp = first;
if( first == last )
{
first = last = nullptr;
}
else
{
first = first->next;
}
delete temp;
size--;
}
/**
* Accessor to return the da.
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.
JAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdfarpaqindia
JAVA
LAB #8 - ARRAY BASED LISTS
The next exercise is based on this implemetation for an UnorderedArrayList of integers:
//Interface: ArrayListADT
//works for int
public interface ArrayListADT {
public boolean isEmpty(); //Method to determine whether the list is empty.
public boolean isFull(); //Method to determine whether the list is full.
public int listSize(); //Method to return the number of elements in the list.
public int maxListSize(); //Method to return the maximum size of the list.
public void print(); //Method to output the elements of the list.
public boolean isItemAtEqual(int location, int item); //Method to determine whether item is
the same as the item in the list at location.
public void insertAt(int location, int insertItem); //Method to insert insertItem in the list at
the position
public void insertEnd(int insertItem); //Method to insert insertItem at the end of the list.
public void removeAt(int location); //Method to remove the item from the list at location.
public int retrieveAt(int location); //Method to retrieve the element from the list at location.
public void replaceAt(int location, int repItem); //Method to replace the element in the list at
location with repItem.
public void clearList(); //Method to remove all the elements from the list.
public int search(int searchItem); //Method to determine whether searchItem is in the list.
public void remove(int removeItem); //Method to remove an item from the list.
}
//Class: ArrayListClass implements
//Interface: ArrayListADT
public abstract class ArrayListClass implements ArrayListADT {
protected int length; //to store the length of the list
protected int maxSize; //to store the maximum size of the list
protected int[] list; //array to hold the list elements
//Default constructor
public ArrayListClass() {
maxSize = 100;
length = 0;
list = new int[maxSize];
}
//Alternate Constructor
public ArrayListClass(int size) {
if(size <= 0) {
System.err.println(\"The array size must be positive. Creating an array of size 100.\");
maxSize = 100;
}
else
maxSize = size;
length = 0;
list = new int[maxSize];
}
public boolean isEmpty() {
return (length == 0);
}
public boolean isFull() {
return (length == maxSize);
}
public int listSize() {
return length;
}
public int maxListSize() {
return maxSize;
}
public void print() {
for (int i = 0; i < length; i++)
System.out.print(list[i] + \" \");
System.out.println();
}
public boolean isItemAtEqual(int location, int item) {
if (location < 0 || location >= length) {
System.err.println(\"The location of the item to be compared is out of range.\");
return false;
}
return list[location]== item;
}
public void clearList() {
for (int i = 0; i < length; i++)
list[i] = 0;
length = 0;
System.gc(); //invoke the Java garbage collector
}
public void removeAt(int location) {
if (location < 0 || location >= length)
System.err.println(\"The location of the item to be removed is out of range.\");
else {
for(int i = location; i < length - 1; i++)
list[i] = list[i + 1.
Lab_3- Objective- Experiment with Lists- Stacks- and Queues- Simulate.docxrennaknapp
Lab_3: Objective: Experiment with Lists, Stacks, and Queues: Simulate an OS task manager
Assignment:
Using the startup code, implement the following:
1-Create List L1 of 10 elements (task IDs), e.g. L1 = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10;
2-Insert a new list element in between (at every other element), such as: 1,100, 2,200, 3,300, 4,400, ... 10,1000;
Simulate a new CPU core assignment:
3-Create another List L2, and extract the newly inserted elements into this new list L2
i.e. L1 should go back to the original list: L1 = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
L2 should be: 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000
Start executing:
4-Create a Queue Q1 by extracting L1, and inserting L2 elements: i.e. Q should start with: 1,2,3, ... 10, and (10, 20 ... 100) will be inserted
Q1=1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000
Label tasks as finished with the possibility of revisiting a task, such as:
5-Create a Stack S1 which by deleting the elements of Q1 and inserting them in L1
6-Pop out all elements of the Stack, i.e. should end up with an empty stack
Extra credit: Simulate a re-executed task, i.e. Pop out a task out of the Stack and reinsert, this simulate a failed task.
7-Verify the functionality and capture the results in a report form.
List.h
main.cpp
#include "List.h"
#include <stdlib.h>
#include <iostream>
using namespace std;
template <typename Object>
class Stack
{
public:
bool isEmpty() const
{
return theList.empty();
}
const Object& top() const
{
return theList.front();
}
void push(const Object& x)
{
theList.push_front(x);
}
void pop(Object& x)
{
x = theList.front(); theList.pop_front();
}
private:
List<Object> theList;
};
template <typename Object>
class Queue
{
public:
bool isEmpty() const
{
return theList.empty();
}
const Object& getFront() const
{
return theList.front();
}
void enqueue(const Object& x)
{
theList.push_back(x);
}
void dequeue(Object& x)
{
x = theList.front(); theList.pop_front();
}
private:
List<Object> theList;
};
int main()
{
int i;
const int N = 10;
List<int> L1;
Stack<int> S1;
Queue<int> Q1;
List<int>::iterator node; //Variable to keep track of the position as we traverse
// List Section example:
//Q1: Create List L1 of 10 elements, e.g. L1 = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10;
// create the list array as a starting point:
for (i = N; i > 0; --i)
{
L1.push_front(i);
}
// show L1 with an iterator
cout << "List L1 is:" << endl;
for (auto it = L1.begin(); it != L1.end(); ++it)
{
cout << *it << ' ';
}
// Stack Section example:
//
// Stack to be created per the above assignment requirment
cout << "\nStack S1 is:" << endl;;
for (i = N - 1; i >= 0; --i)
{
S1.push(i);
cout << S1.top() << " " << endl;
}
while (!S1.isEmpty())
{
cout << S1.top() << endl;
S1.pop(i);
}
// Queue section, to be created per the above assignment requirment
//
//
return 0;
}
please answer with C++ code thank you!
private: int theSize; Node *head.
This document summarizes Chapter 2 on arrays and structures from a textbook on data structures in C. It outlines key topics like the array abstract data type, structures and unions, polynomial and sparse matrix abstract data types, multidimensional arrays, and strings. Examples are provided on implementing arrays, structures, polynomials, and various operations like addition and multiplication on polynomials.
This document summarizes Chapter 2 on arrays and structures from a textbook on data structures in C. It covers various abstract data types including arrays, polynomials, sparse matrices, and strings. It provides examples of implementing one-dimensional and multi-dimensional arrays in C. Structures and unions are described as a way to group heterogeneous data. Self-referential structures and implementation of abstract data types using arrays are also discussed.
2.(Sorted list array implementation)This sorted list ADT discussed .pdfarshin9
2.(Sorted list: array implementation)This sorted list ADT discussed in class should be extended
by the addition of two new methods:
//Interface: ArrayListADT
//works for int
public interface ArrayListADT {
public boolean isEmpty(); //Method to determine whether the list is empty.
public boolean isFull(); //Method to determine whether the list is full.
public int listSize(); //Method to return the number of elements in the list.
public int maxListSize(); //Method to return the maximum size of the list.
public void print(); //Method to output the elements of the list.
public boolean isItemAtEqual(int location, int item); //Method to determine whether item is
the same as the item in the list at location.
public void insertAt(int location, int insertItem); //Method to insert insertItem in the list at
the position
public void insertEnd(int insertItem); //Method to insert insertItem at the end of the list.
public void removeAt(int location); //Method to remove the item from the list at location.
public int retrieveAt(int location); //Method to retrieve the element from the list at location.
public void replaceAt(int location, int repItem); //Method to replace the element in the list at
location with repItem.
public void clearList(); //Method to remove all the elements from the list.
public int search(int searchItem); //Method to determine whether searchItem is in the list.
public void remove(int removeItem); //Method to remove an item from the list.
}
//Class: ArrayListClass implements
//Interface: ArrayListADT
public abstract class ArrayListClass implements ArrayListADT {
protected int length; //to store the length of the list
protected int maxSize; //to store the maximum size of the list
protected int[] list; //array to hold the list elements
//Default constructor
public ArrayListClass() {
maxSize = 100;
length = 0;
list = new int[maxSize];
}
//Alternate Constructor
public ArrayListClass(int size) {
if(size <= 0) {
System.err.println(\"The array size must be positive. Creating an array of size 100.\");
maxSize = 100;
}
else
maxSize = size;
length = 0;
list = new int[maxSize];
}
public boolean isEmpty() {
return (length == 0);
}
public boolean isFull() {
return (length == maxSize);
}
public int listSize() {
return length;
}
public int maxListSize() {
return maxSize;
}
public void print() {
for (int i = 0; i < length; i++)
System.out.print(list[i] + \" \");
System.out.println();
}
public boolean isItemAtEqual(int location, int item) {
if (location < 0 || location >= length) {
System.err.println(\"The location of the item to be compared is out of range.\");
return false;
}
return list[location]== item;
}
public void clearList() {
for (int i = 0; i < length; i++)
list[i] = 0;
length = 0;
System.gc(); //invoke the Java garbage collector
}
public void removeAt(int location) {
if (location < 0 || location >= length)
System.err.println(\"The location of the item to be removed is out of range.\");
else {
for(int i = location; i < length - 1; i++)
list[i] .
Design your own List ADT named StringList to provide the following .pdfprajeetjain
Design your own List ADT named StringList to provide the following operations on a list
object: 1. add (void add(String item) 2. remove (void remove(int index) and void
remove(String item)) 3. size() (int size()) 4. isEmpty (boolean isEmpty() ) 5. indexOf (int
indexOf(String item)) 6. hasItem (boolean hasItem(String item) ) 7. isFull (boolean isFull() ) 8.
getByIndex (String getByIndex(int index)) 9. toString (String toString(), which returns items in
the list in the format as specified below: [Bottle water, Turkey, Oil, Banana] You
are required to use array to implement this ADT. Array only, no other data structures can be used
to implement the structure.
Solution
public class ADT
{
String a[] = new String[1000];
int len=0;
void add(String s)//add item to array
{
a[len++]=s;
System.out.println(\"\ data added to array\ \");
}
void remove(String s)//remove item from array
{
int i,j;
i = indexOf(s);
if(i!=-1){
for(j=i;j.
ReversePoem.java ---------------------------------- public cl.pdfravikapoorindia
ReversePoem.java :-
---------------------------------
public class ReversePoem {
/*This programs has you display a pessimistic poem from a list of phrases*/
// and then reverse the phrases to find another more optimistic poem.
public static void main(String[] args) throws Exception
{
//Queue object
MyQueue queue = new MyQueue<>();
//Stack object
MyStack stack = new MyStack<>();
//String buffer to apppend all Strings
StringBuffer sb = new StringBuffer();
// Create a single String object from the 16 Strings below
String set1 = \"I am part of a lost generation#and I refuse to believe that#\";
sb.append(set1);
String set2 = \"I can change the world#I realize this may be a shock but#\";
sb.append(set2);
String set3 = \"\'Happiness comes from within\'#is a lie, and#\";
sb.append(set3);
String set4 = \"\'Money will make me happy\'#So in 30 years I will tell my children#\";
sb.append(set4);
String set5 = \"they are not the most important thing in my life#\";
sb.append(set5);
String set6 = \"My employer will know that#I have my priorities straight because#\";
sb.append(set6);
String set7 = \"work#is more important than#family#I tell you this#\";
sb.append(set7);
String set8 = \"Once upon a time#Families stayed together#\";
sb.append(set8);
String set9 = \"but this will not be true in my era#\";
sb.append(set9);
String set10 = \"This is a quick fix society#Experts tell me#\";
sb.append(set10);
String set11 = \"30 years from now, I will be celebrating the 10th anniversary of my
divorce#\";
sb.append(set11);
String set12 = \"I do not concede that#I will live in a country of my own making#\";
sb.append(set12);
String set13 = \"In the future#Environmental destruction will be the norm#\";
sb.append(set13);
String set14 = \"No longer can it be said that#My peers and I care about this earth#\";
sb.append(set14);
String set15 = \"It will be evident that#My generation is apathetic and lethargic#\";
sb.append(set15);
String set16 = \"It is foolish to presume that#There is hope#\";
sb.append(set16);
String finalString = sb.toString();
String itmes[] = finalString.split(\"#\");
System.out.println(\"========== Original Phrase ==============\");
for(int i = 0 ; i < itmes.length;i++){
queue.enqueue(itmes[i]);
System.out.println(itmes[i]);
}
for(int i = 0 ; i < itmes.length;i++){
stack.push(queue.dequeue());
}
System.out.println(\"========== Reverse Phrase ==============\");
for(int i = 0 ; i < itmes.length;i++){
System.out.println(stack.pop());
}
/* You are given a list of phrases in Strings; the phrases
are separated by pound signs: \'#\':
1. Create a single String object from this list.
2. Then, split the String of phrases into an array of
phrases using the String split method.
3. Display a poem by walking through the array and
displaying each phrase one per line.
4. And, at the same time, place each phrase on a
MyQueue object using only the enqueue method.
5. After all the phrases have been placed on the queue,
transfer the phrases from the MyQueue object to a
MyS.
This document describes the ArrayLinearList class, which implements a linear list using an array. It includes methods for creating empty lists, adding and removing elements, checking sizes, and converting the list to a string. The class uses an array to store elements, and resizes the array when needed to add elements. Methods are provided for common list operations like get, indexOf, and remove.
Refer to my progress on this assignment belowIn this problem you w.pdfarishmarketing21
Refer to my progress on this assignment below
In this problem you will make it “more” object-oriented in the following ways:
-You will change its name to SortedList
-You will change the constructor that takes no arguments to be more traditional and initialize the
member fields to dummy values.
-You will add a constructor that takes in an initialized array and a size
-You will add an insert function that adds a value to the list and maintains its sorted-ness
-You will add a quicksort function check the below code.
-You will make updates as necessary to the main function so that it still runs and tests your code.
The code below seems to sort correctly but it skips over some items in the array and I am not
sure what is happening. Please help! Thanks!
import java.util.Scanner;
class SortedList
{
private static int array[];
private static int n;
public SortedList()
{
Scanner in = new Scanner(System.in);
System.out.println(\"Enter number of elements\");
n = in.nextInt();
array = new int[n];
if(n == 0) {
System.out.print(\"Since no arguments array set to: \");
} else {
System.out.print(\"Creating array size \" + n + \": \");
}
for(int i = 0; i < n; i++)
{
array[i] = 0;
}
//System.out.println(\"Enter \" + n + \" integers in ascending order\");
/*for (c = 0; c < n; c++)
array[c] = in.nextInt();*/
for(int i = 0; i < n; i++)
{
System.out.print(array[i] + \" \");
}
System.out.print(\"\ \");
}
public SortedList(int a[], int size)
{
array = a;
n = size;
}
public int binsearch(int search)
{
int first, last, middle;
first = 0;
last = n - 1;
middle = (first + last)/2;
while( first <= last )
{
if ( array[middle] < search )
first = middle + 1;
else if ( array[middle] == search )
{
//System.out.println(search + \" found at location \" + (middle + 1) + \".\");
return middle+1;//+1 for the non-CS people who don\'t start counting at zero.
}
else
last = middle - 1;
middle = (first + last)/2;
}
return -1;
//System.out.println(search + \" is not present in the list.\ \");
}
public static int partition(int input[], int p, int r)
{
int pivot = input[r];
while(p < r)
{
while(input[p] < pivot)
{
p++;
}
while(input[r] > pivot)
{
r--;
}
if(input[p] == input[r])
{
p++;
}
else if(p < r)
{
int tmp = input[p];
input[p] = input[r];
input[r] = tmp;
}
}
return r;
}
public static void quicksort(int input[], int p, int r)
{
if(p < r)
{
int j = partition(input, p, r);
quicksort(input, p, j-1);
quicksort(input, j+1, r);
}
}
public static void insert(int value, int cell)
{
array[cell] = value;
quicksort(array, 0, n-1);
}
public static void main(String args[])
{
int c;
Scanner in = new Scanner(System.in);
SortedList b = new SortedList();
System.out.println(\"Input numbers\");
for(int i = 0; i < n; i++)
{
c = in.nextInt();
in.nextLine();
insert(c, i);
}
in.close();
for(int j = 0; j < n; j++)
{
System.out.print(array[j] + \", \");
}
}
}
Solution
//the whole program that you wrote is correct except one line , when you call the quicksort
everytime you insert a //value dont pass n pass the i.
This document provides information on arrays in C programming. It defines an array as a collection of data storage locations with the same name and data type. It discusses array declaration, initialization, accessing elements using indexes, insertion and deletion of elements, and multi-dimensional arrays. Code examples are provided to demonstrate printing the contents of 1D, 2D and 3D arrays. The document also lists some reference books for learning C programming.
Engineering lecture ppt by venay magenvenaymagen19
Venay Magen likes the shading red, particularly on Tuesdays. He cherishes to drink bourbon (on all days). He figured out how to drink whisky from his youth companion Zippo, when they went to class together at Mount Temple Comprehensive School. He is best known as the lead vocalist for the band MN3.
Labprogram.java
LinkedList.java
import java.util.NoSuchElementException;
public class LinkedList {
private class Node {
private T data;
private Node next;
private Node prev;
public Node(T data) {
this.data = data;
this.next = null;
this.prev = null;
}
}
private int length;
private Node first;
private Node last;
private Node iterator;
/**** CONSTRUCTORS ****/
public LinkedList() {
first = null;
last = null;
iterator = null;
length = 0;
}
/**
* Converts the given array into a LinkedList
*
* @param array the array of values to insert into this LinkedList
* @postcondition
*/
public LinkedList(T[] array) {
}
/**
* Instantiates a new LinkedList by copying another List
*
* @param original the LinkedList to copy
* @postcondition a new List object, which is an identical,
* but separate, copy of the LinkedList original
*/
public LinkedList(LinkedList original) {
}
public T getFirst() throws NoSuchElementException {
if (isEmpty()) {
throw new NoSuchElementException("The list is empty");
}
return first.data;
}
public T getLast() throws NoSuchElementException {
if (isEmpty()) {
throw new NoSuchElementException("The list is empty");
}
return last.data;
}
public T getIterator() throws NullPointerException {
if (iterator != null) {
return iterator.data;
} else {
throw new NullPointerException("Iterator is off the end opf the list.");
}
}
public int getLength() {
return length;
}
public boolean isEmpty() {
return length == 0;
}
public boolean offEnd() {
return iterator == null;
}
public void addFirst(T data) {
Node newNode = new Node(data);
if (isEmpty()) {
first = newNode;
last = newNode;
} else {
newNode.next = first;
first.prev = newNode;
first = newNode;
}
length++;
}
public void addLast(T data) {
Node newNode = new Node(data);
if (isEmpty()) {
first = newNode;
last = newNode;
} else {
last.next = newNode;
newNode.prev = last;
last = newNode;
}
length++;
}
public void addIterator(T data) throws NullPointerException {
if (offEnd()) {
throw new NullPointerException("addIterator Iterator is off end.");
}
if (iterator == last) {
addLast(data);
} else {
Node newNode = new Node(data);
Node next = iterator.next;
newNode.next = next;
newNode.prev = iterator;
iterator.next = newNode;
next.prev = newNode;
length++;
}
}
public void removeFirst() throws NoSuchElementException {
if (isEmpty()) {
throw new NoSuchElementException("The list is empty");
}
if (length == 1) {
first = null;
last = null;
iterator = null;
} else {
if (iterator == first) {
iterator = null;
}
first = first.next;
first.prev = null;
}
length--;
}
public void removeLast() throws NoSuchElementException {
if (isEmpty()) {
throw new NoSuchElementException("The list is empty");
}
if (length == 1) {
first = null;
last = null;
iterator = null;
} else {
if (iterator == last) {
iterator = null;
}
last = last.prev;
last.next = null;
}
length--;
}
public void removeIterator() throws NullPointerException {
if (offEnd()) {
throw new NullPointerException("Iterator is off the end opf the list.");
}
if (iterator .
This document discusses arrays in C++. It defines an array as a collection of the same type of data. Arrays can be initialized using a loop or by declaring and initializing in one step. Multidimensional arrays represent 2D data with rows and columns. Examples are provided to demonstrate reading from and printing to arrays, as well as searching, copying, and calculating averages of array elements.
I need help with this code working Create another project and add yo.pdffantoosh1
I need help with this code working Create another project and add your jar file in this project. In
the main method of App class of this second project test your MyArrayList class. It is mandatory
to follow the instructions to get full credit. You need to perform the following actions. 1. Create
five strings, A1",,'B2",,'C3",'D4",'E5" 2. Save these Strings in your MyArrayList 3. Print a
message "Displaying List" 4. Display the list 5. Insert another String in your MyArrayList at
location 2 6. Print a message "Inserting Item" 7. Display the list 8. Remove String at location 0 9.
Print a message "Removing Item" 10. Display the list 11. Print a message "Setting a String" 12.
Set a new String in location 1 13. Display the list 14. Check whether "D4" is present in the list or
not, print an appropriate message 15. Find the index of "E5" in your list, print an appropriate
message 16. Print a message "Emptying List" 17. Empty the list 18. Print the size of the list
These steps check most of your MyArrayList functionality. I will also perform my own checks of
your code while grading. Deliverable: a. Copy the utils.jar file in your project folder. b. Make a
zip file of full project, not the src folder only or java files only. c. Submit the zip file. Grading
Rubric: The project is not submitted as required: 0 points
st.java J MyArrayList.java 2 J App.java 2 J MyFile.java 2 rc >J MyArrayList.java >q&
MyArrayList > get(int) public class MyArrayList implements MyList \{ Object [] obj = new
Object [1]; int size; public int size()\{ return size; \} public object get(int index) if (index <0
index >= size ){// throw new indexo return obj [index]; \} return index; // this should be deleted
after public void add (Object 0 ) \{ //if this test fails there is a space in the array. // it will pass
itself. if ( size == obj. length ){ Object [] obj2 = new 0 bject [obj. length 2]; for(int i=0;i<0bj.
length; i++){ obj2[i]=obj [i] ; \} obj=obj2; \} obj [ size ]=0; size++; \} public void add(int index,
Object o) \{ if(index > size || index <0 ) \{ throw new IndexOut0fBoundsException(index); \} if
(size == obj. length ){ Object [] obj2 = new Object [obj. length 2 ]; for(int i=0;i<0bj. length;
i++){ obj 2[i]=obj[i]; \} obj=obj2; \} if (index i=size;i>= index; i){ nhi [i=nhii1 : Ln 16, Col 56
Spaces: 4 UTF-8 LF \{\} Java
In this lab you will add an interface to the MyUtils project, and implement it in your
MyArrayList class in the MyUtils project. You will test the newly added functionality of your
MyArrayList class in another project. The UML for the Interface is as follows S Description of
methods Following method are self-explanatory: size(), get(int index), add (object o), remove
(int index), and isEmpty). Below is the description of all other methods. void add(int index,
Object o) inserts the given reference of object o at location index, making all entries move down
a spot. void remove (Object o) removes the first occurrence of object o in the list, moving all
entries .
The document discusses stacks and their implementation and applications. Stacks are LIFO data structures that can be implemented using arrays. Key operations on stacks include push, pop, peek, isEmpty and isFull. Stacks have various applications including expression evaluation, recursion, function calls and memory management. Stacks can grow either upwards or downwards in the array.
The document discusses arrays in C programming. It defines key concepts like array representation, index starting from 0, memory representation of arrays, and address calculation of array elements. It also covers various array operations like creation, copying, deletion, insertion, sorting, and representation of arrays as abstract data types. Multidimensional arrays and their row-major and column-major representations are explained along with examples.
lab08/build.bat
@echo off
cls
set DRIVE_LETTER=%1:
set PATH=%DRIVE_LETTER%\MinGW\bin;%DRIVE_LETTER%\MinGW\msys\1.0\bin;%DRIVE_LETTER%\MinGW\gtkmm3\bin;%DRIVE_LETTER%\MinGW\gtk\bin;c:\Windows;c:\Windows\system32
set PROJECT_PATH=.
make DRIVE_LETTER="%DRIVE_LETTER%" PROJECT_DIR="%PROJECT_PATH%"
lab08/CSC2110/CD.h
#if !defined CD_H
#define CD_H
#include "Song.h"
#include "Text.h"
using CSC2110::String;
#include "ListArray.h"
using CSC2110::ListArray;
namespace CSC2110
{
class CD
{
private:
String* artist;
String* title;
int year;
int rating;
int num_tracks;
ListArray<Song>* songs;
public:
CD(String* artist, String* title, int year, int rating, int num_tracks);
virtual ~CD();
String* getKey();
void addSong(String* title, String* length);
void displayCD();
static ListArray<CD>* readCDs(const char* file_name);
static int compare_items(CD* one, CD* two);
static int compare_keys(String* sk, CD* cd);
static char getRadixChar(CD* cd, int index); //1-based
};
}
#endif
lab08/CSC2110/Double.h
#if !defined (DOUBLE_H)
#define DOUBLE_H
namespace CSC2110
{
class Double
{
private:
double value;
public:
Double(double val);
~Double();
double getValue();
};
}
#endif
lab08/CSC2110/HighPerformanceCounter.h
#if !defined (HIGHPERFORMANCECOUNTER_H)
#define HIGHPERFORMANCECOUNTER_H
namespace CSC2110
{
class HighPerformanceCounter
{
private:
double micro_spt; //micro_seconds per tick
HighPerformanceCounter();
static HighPerformanceCounter* hpc;
static int getTicksPerSecond();
public:
virtual ~HighPerformanceCounter();
static HighPerformanceCounter* getHighPerformanceCounter();
int getCurrentTimeInTicks();
double getTimeDifferenceInMicroSeconds(int start_time, int end_time);
};
}
#endif
lab08/CSC2110/Integer.h
#if !defined (INTEGER_H)
#define INTEGER_H
namespace CSC2110
{
class Integer
{
private:
int value;
public:
Integer(int val);
virtual ~Integer();
int getValue();
};
}
#endif
lab08/CSC2110/Keyboard.h
#if !defined KEYBOARD_H
#define KEYBOARD_H
#include "Text.h"
using CSC2110::String;
#include <string>
using namespace std;
namespace CSC2110
{
class Keyboard
{
private:
Keyboard();
public:
virtual ~Keyboard();
static Keyboard* getKeyboard();
//pre: the string (character literal) that will prompt the user for input
//post: the input read from the keyboard interpreted as an int is returned
int readInt(string prompt);
int getValidatedInt(string prompt, int min, int max);
//pre: the string that will prompt the user for input
//post: the input read from the keyboard interpreted as a double is returned
double readDouble(string prompt);
double getValidatedDouble(string prom ...
How do you stop infinite loop Because I believe that it is making a.pdffeelinggift
How do you stop infinite loop? Because I believe that it is making an infinite circular list.
c++ code:
Here is the list class:
#ifndef LIN_J_LIST
#define LIN_J_LIST
typedef unsigned int uint;
#include
#include
using namespace std;
/**
* a simplified generic singly linked list class to illustrate C++ concepts
* @author Jerry Lin
* @version 2/17/17
*/
template< typename Object >
class List
{
private:
/**
* A class to store data and provide a link to the next node in the list
*/
class Node
{
public:
/**
* The constructor
* @param data the data to be stored in this node
*/
explicit Node( const Object & data )
: data{ data }, next{ nullptr } {}
Object data;
Node * next;
};
public:
/**
* The constructor for an empty list
*/
List()
: size{ 0 }, first{ nullptr }, last{ nullptr } {}
/**
* the copy constructor-creates and copy the list
*/
List( List && rhs ) = delete;
List( const List & rhs )
{
count = 0;
size = 0;
if(rhs.size != 0)
{
push_front(rhs.front());
Node * current = rhs.first;
Node * tempNode = first;
size++;
while(current->next != nullptr)
{
current = current->next;
Node *newNode = new Node(current->data); //transfer the data. basic op.
count++;
tempNode->next = newNode;
last = newNode;
tempNode = tempNode->next;
size++;
}
}
// you document and implement this method
}
/**
* the operator= method-copies the list
*/
List & operator=( List && rhs) = delete;
List & operator=( const List & rhs )
{
count = 0;
size = 0;
if( size != 0 )
{
Node * current = first;
Node * temp;
while( current != nullptr )
{
temp = current;
current = current->next;
delete temp;
}
}
if(rhs.size!= 0)
{
push_front(rhs.front());
Node * current = rhs.first;
Node * tempNode = first; //create a temporary to store
size++;
while(current -> next != nullptr)
{
current = current->next;
Node *newNode = new Node(current->data); //transfer the data. basic op
count++;
tempNode->next = newNode;
last = newNode;
tempNode = tempNode -> next;
size++;
}
}
return *this;
// you document and implement this method
}
/**
* accessor
* @return count
*/
int get_count() const
{
return count;
}
/**
* The destructor that gets rid of everything that\'s in the list and
* resets it to empty. If the list is already empty, do nothing.
*/
~List()
{
if( size != 0 )
{
Node * current = first;
Node * temp;
while( current != nullptr )
{
temp = current;
current = current->next;
delete temp;
}
}
}
/**
* Put a new element onto the beginning of the list
* @param item the data the new element will contain
*/
void push_front( const Object& item )
{
Node * new_node = new Node( item );//basic op.
if(is_empty())
{
last = new_node;
}
else
{
new_node->next = first;
}
first = new_node;
size++;
/* you complete the rest */
}
/**
* Remove the element that\'s at the front of the list. Causes an
* assertion error if the list is empty.
*/
void pop_front()
{
assert( !is_empty() );
Node * temp = first;
if( first == last )
{
first = last = nullptr;
}
else
{
first = first->next;
}
delete temp;
size--;
}
/**
* Accessor to return the da.
Similar to Data Structures and Agorithm: DS 02 Array List.pptx (20)
Determination of Equivalent Circuit parameters and performance characteristic...pvpriya2
Includes the testing of induction motor to draw the circle diagram of induction motor with step wise procedure and calculation for the same. Also explains the working and application of Induction generator
Prediction of Electrical Energy Efficiency Using Information on Consumer's Ac...PriyankaKilaniya
Energy efficiency has been important since the latter part of the last century. The main object of this survey is to determine the energy efficiency knowledge among consumers. Two separate districts in Bangladesh are selected to conduct the survey on households and showrooms about the energy and seller also. The survey uses the data to find some regression equations from which it is easy to predict energy efficiency knowledge. The data is analyzed and calculated based on five important criteria. The initial target was to find some factors that help predict a person's energy efficiency knowledge. From the survey, it is found that the energy efficiency awareness among the people of our country is very low. Relationships between household energy use behaviors are estimated using a unique dataset of about 40 households and 20 showrooms in Bangladesh's Chapainawabganj and Bagerhat districts. Knowledge of energy consumption and energy efficiency technology options is found to be associated with household use of energy conservation practices. Household characteristics also influence household energy use behavior. Younger household cohorts are more likely to adopt energy-efficient technologies and energy conservation practices and place primary importance on energy saving for environmental reasons. Education also influences attitudes toward energy conservation in Bangladesh. Low-education households indicate they primarily save electricity for the environment while high-education households indicate they are motivated by environmental concerns.
Sri Guru Hargobind Ji - Bandi Chor Guru.pdfBalvir Singh
Sri Guru Hargobind Ji (19 June 1595 - 3 March 1644) is revered as the Sixth Nanak.
• On 25 May 1606 Guru Arjan nominated his son Sri Hargobind Ji as his successor. Shortly
afterwards, Guru Arjan was arrested, tortured and killed by order of the Mogul Emperor
Jahangir.
• Guru Hargobind's succession ceremony took place on 24 June 1606. He was barely
eleven years old when he became 6th Guru.
• As ordered by Guru Arjan Dev Ji, he put on two swords, one indicated his spiritual
authority (PIRI) and the other, his temporal authority (MIRI). He thus for the first time
initiated military tradition in the Sikh faith to resist religious persecution, protect
people’s freedom and independence to practice religion by choice. He transformed
Sikhs to be Saints and Soldier.
• He had a long tenure as Guru, lasting 37 years, 9 months and 3 days
Supermarket Management System Project Report.pdfKamal Acharya
Supermarket management is a stand-alone J2EE using Eclipse Juno program.
This project contains all the necessary required information about maintaining
the supermarket billing system.
The core idea of this project to minimize the paper work and centralize the
data. Here all the communication is taken in secure manner. That is, in this
application the information will be stored in client itself. For further security the
data base is stored in the back-end oracle and so no intruders can access it.
This study Examines the Effectiveness of Talent Procurement through the Imple...DharmaBanothu
In the world with high technology and fast
forward mindset recruiters are walking/showing interest
towards E-Recruitment. Present most of the HRs of
many companies are choosing E-Recruitment as the best
choice for recruitment. E-Recruitment is being done
through many online platforms like Linkedin, Naukri,
Instagram , Facebook etc. Now with high technology E-
Recruitment has gone through next level by using
Artificial Intelligence too.
Key Words : Talent Management, Talent Acquisition , E-
Recruitment , Artificial Intelligence Introduction
Effectiveness of Talent Acquisition through E-
Recruitment in this topic we will discuss about 4important
and interlinked topics which are
Tools & Techniques for Commissioning and Maintaining PV Systems W-Animations ...Transcat
Join us for this solutions-based webinar on the tools and techniques for commissioning and maintaining PV Systems. In this session, we'll review the process of building and maintaining a solar array, starting with installation and commissioning, then reviewing operations and maintenance of the system. This course will review insulation resistance testing, I-V curve testing, earth-bond continuity, ground resistance testing, performance tests, visual inspections, ground and arc fault testing procedures, and power quality analysis.
Fluke Solar Application Specialist Will White is presenting on this engaging topic:
Will has worked in the renewable energy industry since 2005, first as an installer for a small east coast solar integrator before adding sales, design, and project management to his skillset. In 2022, Will joined Fluke as a solar application specialist, where he supports their renewable energy testing equipment like IV-curve tracers, electrical meters, and thermal imaging cameras. Experienced in wind power, solar thermal, energy storage, and all scales of PV, Will has primarily focused on residential and small commercial systems. He is passionate about implementing high-quality, code-compliant installation techniques.
Build the Next Generation of Apps with the Einstein 1 Platform.
Rejoignez Philippe Ozil pour une session de workshops qui vous guidera à travers les détails de la plateforme Einstein 1, l'importance des données pour la création d'applications d'intelligence artificielle et les différents outils et technologies que Salesforce propose pour vous apporter tous les bénéfices de l'IA.
A high-Speed Communication System is based on the Design of a Bi-NoC Router, ...DharmaBanothu
The Network on Chip (NoC) has emerged as an effective
solution for intercommunication infrastructure within System on
Chip (SoC) designs, overcoming the limitations of traditional
methods that face significant bottlenecks. However, the complexity
of NoC design presents numerous challenges related to
performance metrics such as scalability, latency, power
consumption, and signal integrity. This project addresses the
issues within the router's memory unit and proposes an enhanced
memory structure. To achieve efficient data transfer, FIFO buffers
are implemented in distributed RAM and virtual channels for
FPGA-based NoC. The project introduces advanced FIFO-based
memory units within the NoC router, assessing their performance
in a Bi-directional NoC (Bi-NoC) configuration. The primary
objective is to reduce the router's workload while enhancing the
FIFO internal structure. To further improve data transfer speed,
a Bi-NoC with a self-configurable intercommunication channel is
suggested. Simulation and synthesis results demonstrate
guaranteed throughput, predictable latency, and equitable
network access, showing significant improvement over previous
designs
Blood finder application project report (1).pdfKamal Acharya
Blood Finder is an emergency time app where a user can search for the blood banks as
well as the registered blood donors around Mumbai. This application also provide an
opportunity for the user of this application to become a registered donor for this user have
to enroll for the donor request from the application itself. If the admin wish to make user
a registered donor, with some of the formalities with the organization it can be done.
Specialization of this application is that the user will not have to register on sign-in for
searching the blood banks and blood donors it can be just done by installing the
application to the mobile.
The purpose of making this application is to save the user’s time for searching blood of
needed blood group during the time of the emergency.
This is an android application developed in Java and XML with the connectivity of
SQLite database. This application will provide most of basic functionality required for an
emergency time application. All the details of Blood banks and Blood donors are stored
in the database i.e. SQLite.
This application allowed the user to get all the information regarding blood banks and
blood donors such as Name, Number, Address, Blood Group, rather than searching it on
the different websites and wasting the precious time. This application is effective and
user friendly.
3rd International Conference on Artificial Intelligence Advances (AIAD 2024)GiselleginaGloria
3rd International Conference on Artificial Intelligence Advances (AIAD 2024) will act as a major forum for the presentation of innovative ideas, approaches, developments, and research projects in the area advanced Artificial Intelligence. It will also serve to facilitate the exchange of information between researchers and industry professionals to discuss the latest issues and advancement in the research area. Core areas of AI and advanced multi-disciplinary and its applications will be covered during the conferences.
Beckhoff Programmable Logic Control Overview Presentation
Data Structures and Agorithm: DS 02 Array List.pptx
1. Data Structure
Lecture No. 2
Array List
Engr. Rashid Farid Chishti
http://youtube.com/rfchishti
http://sites.google.com/site/chishti
International Islamic University H-10, Islamabad, Pakistan
Video Lecture
2. We have designed the interface for the List; we now must consider how to
implement that interface.
Implementing Lists using an array:
for example, the list of integers {2, 6, 8, 7, 1} could be represented as:
insert(3,9): The new list would thus be: {2, 6, 8, 9, 7, 1}
We have to shift every element to the right of one place from current position to make
space for the new element ‘9’.
Implementing Array List
Index No. 0 1 2 3 4 5 6 7 Size
Data 2 6 8 7 1 8
Index No. 0 1 2 3 4 5 6 7 Size
Data 2 6 8 7 7 1 8
Index No. 0 1 2 3 4 5 6 7 Size
Data 2 6 8 9 7 1 8
Step 1:
Step 2:
3. insert(3,9):
void insert ( int pos, int num ){
int i;
// Rigt Shift all numbers from pos position.
for ( i = size - 1 ; i > pos ; i-- )
data[i] = data[i - 1] ;
// now place the data at pos position.
data[i] = num ;
}
Implementing Array List
4. Remove(1): Removes the element at the index 1.
We have to shift every element to the left of one place from index number
1 to remove data .
Implementing Array List
Index No. 0 1 2 3 4 5 6 7 Size
Data 2 6 8 9 7 1 8
Index No. 0 1 2 3 4 5 6 7 Size
Data 2 8 9 7 1 8
Step 1:
Step 2:
5. Remove(1):
remove ( int pos )
{
int i;
// Left Shift all numbers from pos position.
for ( i = pos ; i < size ; i++ )
data[i] = data[i + 1] ;
// Fill the right most number with 0 to avoid filling garbage vlaue
data[i - 1] = 0;
}
Implementing Array List
6. Find(9): Find a Number 9 from Array List.
void Find(int Data_to_Search)
{
for(int i=0 ; i < size ; i++ )
if( Data[i] == Data_to_Search ){
cout << num << " is present at index No. "<< i << endl ;
return;
}
cout << "nNot Found "<< num << endl ;
}
Implementing Array List
7. Copy(): Copies a List.
Clear(): clear a list (remove all elements)
Get(?): Get element at a given position
update ( int pos, int num ): replace the element at a given position
with num;
Implementing Array List
8. #include <iostream>
using namespace std;
class List
{
private :
int size;
int *data ;
public :
List();
List(int sz);
void create(int sz);
List copy ();
void clear ();
void insert ( int pos, int num ) ;
void remove ( int pos ) ;
int get(int pos);
8
Example 1: List Using an Array
void update ( int pos, int num );
void find ( int num ) ;
void reverse( ) ;
void display( ) ;
int length();
};
List :: List(){
data = nullptr;
size = 0;
}
List :: List(int sz){
size = sz;
data = new int[size];
for (int i=0 ; i<size ; i++)
data[i] = 0;
}
1 2
9. void List :: create(int sz)
{
size = sz;
data = new int[size];
for (int i=0 ; i<size ; i++)
data[i] = 0;
}
int List::length(){
return (size);
}
List List::copy (){
List temp(size);
for (int i = 0 ; i<size ; i++){
temp.data[i] = data[i];
}
return temp;
}
9
Example 1: List Using an Array
void List::clear (){
if (data != nullptr)
delete [] data;
}
void List :: insert ( int pos, int num ){
int i;
for ( i = size - 1 ; i > pos ; i-- )
data[i] = data[i - 1] ;
data[i] = num ;
}
void List :: remove ( int pos ){
int i;
for ( i = pos ; i < size ; i++ )
data[i] = data[i + 1] ;
data[i - 1] = 0;
}
3 4
10. int List :: get ( int pos ){
return data[pos];
}
void List :: update ( int pos, int num ){
data[pos] = num ;
}
void List :: find ( int num ){
int i;
for ( i = 0 ; i < size ; i++ )
{
if ( data[i] == num ){
cout << "nThe element " << num
<< " is present at index No. "
<< i << endl ; return ;
}
}
cout << "nThe element " << num
<< " is not present" ;
}
10
Example 1: List Using an Array
void List :: display( ) {
cout<< endl ;
for ( int i = 0 ; i < size ; i++ )
cout << " " << data[i] ;
cout << endl;
}
int main( ){
List l1,l2;
l1.create(8);
l1.insert(0,2);l1.insert(1,6);
l1.insert(2,8);l1.insert(3,7);
l1.insert(4,1);l1.display();
l1.insert(3,9); l1.display();
l1.remove(1); l1.display();
return 0;
}
5 6