Question

pls help, idk whats wrong with this Add the reverse() method which reverses the content of...

pls help, idk whats wrong with this

Add the reverse() method which reverses the content of array without using additional array and the rotate(k) method which rotates left the content of array without using additional array by k elements.

import java.util.*;

* Implementation of the ADT List using a fixed-length array.
*
* if insert is successful returns 1, otherwise 0;
* for successful insertion:
* list should not be full and p should be valid.
*
* if delete is successful returns 1, otherwise 0;
* for successful deletion:
* list should not be empty and p should be valid.
*/
public class proj2 implements list{
       // class Variables
protected int n, count;
protected int arr[];   

proj2(int k){ // List Constructor
count = 0;
n = k;
        //Allocate Space for array            
arr = new int[n+1];// index 0 is not used
}
public boolean isEmpty(){
return (count == 0);}
public boolean isFull (){
return (count == n);}
public int   length (){
return count;}

       // insert x at position p
       // for successful insertion:
       // list should not be full and p should be valid.
       //    valid p's are: p >= 1 and p <= count+1    
public int insert(int x, int p){
int i;
System.out.printf("\n Insert %4d at position %2d.", x, p);
if (isFull() || p < 1 || p > count + 1)
return 0;
        // Shift from position p to right
for (i = count ; i >= p ; i--)
arr[i+1] = arr[i];
        // end for
        // insert x at position p          
arr[p] = x;
count++; // increment no. of elements.
return 1; // successful insertion
} // end insert

       // delete x at position p
       // for successful deletion:
       // list should not be empty and p should be valid.
       //    valid p's are: p >= 1 and p <= count    
public int delete(int p){
System.out.printf("\n Delete element at position %2d.", p);
if ( isEmpty() || p < 1 || p > count)
return 0;
        // Shift from position p + 1 to left
for (int i = p ; i < count ; i++)
arr[i] = arr[i+1];
        // end for
count --; // decrement no. of elements
return 1; // successful deletion
}

       // sequential serach for x in the list
       // if successful return position of x in the list,
       // otherwise return 0;
public int serachx(int x){
System.out.printf("\n search for %4d", x);
        // complete the rest
return 1;
}
      
       // print list elements
public void printlist(){
int i;
System.out.print("\n List contents: ");
for (i = 1; i <= count; i++)
System.out.printf("%4d, ", arr[i]);
        // enf for
}
private static void reverse(int a[], int n)

{

for (int i = 0; i < n / 2; i++) // swapping the elements upto n/2 index
  
{
  
int k = a[i];
  
a[i] = a[n - i - 1];
  
a[n - i - 1] = k;
  
}

/*printing the reversed array*/

System.out.print("\nElements of array After the reversing : ");

for (int i = 0; i < n; i++) {
  
System.out.print(a[i]+ " ");
  
}

}

static void rotate(int a[], int n,int k) // method for rotating the elements left

{

System.out.print("\nAfter rotating "+ k +" index left the content of array : ");

for(int i=0;i<n;i++)
  
{
  
// a[i] = a[ ( i + k)%n ];
  
System.out.print( a[ ( i + k)%n ]+" "); // here we are taking nod n beacuse if our left rotaion ie. k value is greater than n then make it zero
  
}

}      

public static void main(String args[]) {
int j, m, k, p, x, s;
try{
Scanner inf = new Scanner(System.in);  
k = inf.nextInt(); // read list size
   // Create a List of type Integer of size n
proj2 lst = new proj2(k);          
  
   // read m elements and insert in the list
m = inf.nextInt(); // read no. of elements to insert
System.out.printf("\nInsert %2d elements in the list", m);
for(j = 1; j <= m; j++){
x = inf.nextInt(); // read x
p = inf.nextInt(); // read position
s = lst.insert(x, p); // insert x at position p
if (s == 1)
System.out.printf("\nInserting %d at position %d was successful", x, p);              
else
System.out.printf("\nInserting %d at position %d was not successful", x, p);
}// end for
System.out.printf("\n\nList content after inserting %d elements", m);
lst.printlist();
  
   // read m positions to delete from list
m = inf.nextInt(); // read no. positions to delete
System.out.printf("\n\nDelete %d elements from list", m);
for(j = 1; j <= m; j++){
p = inf.nextInt(); // read position
s = lst.delete(p);
if ( s == 1)
System.out.printf("\nDeleting element at position %2d was successful", p);
else
System.out.printf("\nDeleting element at position %2d was not successful", p);
}// end for
System.out.printf("\n\nList content after deleting %d elements.", m);
lst.printlist();
inf.close(); // close input file
lst.reverse(); // reverse array elements
System.out.printf("\n\nList content after reversing.");
lst.printlist();
k = inf.nextInt(); // read k for rotate
lst.rotate(k); // rotate left by k elements
System.out.printf("\n\nList content after rotating %d.", k);
lst.printlist();

} catch (Exception e) {System.out.print("\nException " + e + "\n");}
} // end main
}// end class listarr

0 0
Add a comment Improve this question Transcribed image text
Answer #1


ANSWER:-

CODE:-

import java.util.*;

/* Implementation of the ADT List using a fixed-length array.
*
* if insert is successful returns 1, otherwise 0;
* for successful insertion:
* list should not be full and p should be valid.
*
* if delete is successful returns 1, otherwise 0;
* for successful deletion:
* list should not be empty and p should be valid.
*/
public class Proj2{
       // class Variables
protected int n, count;
protected int arr[];

Proj2(int k){ // List Constructor
    count = 0;
    n = k;
            //Allocate Space for array          
    arr = new int[n+1];// index 0 is not used
}
public boolean isEmpty(){
   return (count == 0);
}
public boolean isFull (){
   return (count == n);
}
public int   length (){
    return count;
}

         // insert x at position p
         // for successful insertion:
         // list should not be full and p should be valid.
         //    valid p's are: p >= 1 and p <= count+1  
public int insert(int x, int p){
    int i;
    System.out.printf("\n Insert %4d at position %2d.", x, p);
    if (isFull() || p < 1 || p > count + 1)
      return 0;
            // Shift from position p to right
    for (i = count ; i >= p ; i--)
     arr[i+1] = arr[i];
            // end for
            // insert x at position p        
    arr[p] = x;
    count++; // increment no. of elements.
    return 1; // successful insertion
} // end insert

         // delete x at position p
         // for successful deletion:
         // list should not be empty and p should be valid.
         //    valid p's are: p >= 1 and p <= count  
public int delete(int p){
    System.out.printf("\n Delete element at position %2d.", p);
    if ( isEmpty() || p < 1 || p > count)
      return 0;
            // Shift from position p + 1 to left
    for (int i = p ; i < count ; i++)
      arr[i] = arr[i+1];
            // end for
    count --; // decrement no. of elements
    return 1; // successful deletion
}

         // sequential serach for x in the list
         // if successful return position of x in the list,
         // otherwise return 0;
public int serachx(int x){
    System.out.printf("\n search for %4d", x);
    for(int i=1;i<=count;i++){
      if(arr[i] == x){
        return i;
      }
    }
    return 0;
}
      
         // print list elements
public void printlist(){
    int i;
    System.out.print("\n List contents: ");
    for (i = 1; i <= count; i++)
      System.out.printf("%4d, ", arr[i]);
    System.out.println();
          // enf for
}
private void reverse(int a[])

{

    for (int i = 1; i <= count / 2; i++) // swapping the elements upto n/2 index
    
    {
      int k = a[i];
      
      a[i] = a[count - i+1];
      
      a[count - i+1] = k;
    }
}

void rotate(int k) // method for rotating the elements left

{

    System.out.print("\nAfter rotating "+ k +" index left the content of array : ");

    while(k-->0){
      int i;
      int temp = arr[1];
      for(i=1;i<count;i++){
        arr[i] = arr[i+1];
      }
      arr[i] = temp;
    }

}    

public static void main(String args[]) {
    int j, m, k, p, x, s;
    try{
      Scanner inf = new Scanner(System.in);
      k = inf.nextInt(); // read list size
         // Create a List of type Integer of size n
      Proj2 lst = new Proj2(k);        
      
         // read m elements and insert in the list
      m = inf.nextInt(); // read no. of elements to insert
      System.out.printf("\nInsert %2d elements in the list", m);
      for(j = 1; j <= m; j++){
        x = inf.nextInt(); // read x
        p = inf.nextInt(); // read position
        s = lst.insert(x, p); // insert x at position p
        if (s == 1)
          System.out.printf("\nInserting %d at position %d was successful", x, p);            
        else
         System.out.printf("\nInserting %d at position %d was not successful", x, p);
      }// end for
      System.out.printf("\n\nList content after inserting %d elements", m);
      lst.printlist();
      
         // read m positions to delete from list
      m = inf.nextInt(); // read no. positions to delete
      System.out.printf("\n\nDelete %d elements from list", m);
      for(j = 1; j <= m; j++){
        p = inf.nextInt(); // read position
        s = lst.delete(p);
        if ( s == 1)
         System.out.printf("\nDeleting element at position %2d was successful", p);
        else
         System.out.printf("\nDeleting element at position %2d was not successful", p);
      }// end for
      System.out.printf("\n\nList content after deleting %d elements.", m);
      lst.printlist();
      //inf.close(); // close input file
      lst.reverse(lst.arr); // reverse array elements
      System.out.printf("\n\nList content after reversing.");
      lst.printlist();
      k = inf.nextInt(); // read k for rotate
      lst.rotate(k); // rotate left by k elements
      System.out.printf("\n\nList content after rotating %d.", k);
      lst.printlist();

    } catch (Exception e) {
      System.out.print("\nException " + e + "\n");
    }
} // end main
}

NOTE:- I implemented both reverse and rotate methods in your code.please check once.

If you need any modifications in the code,please comment below.Please give positive rating. THUMBS UP.

                THANK YOU!!!

OUTPUT:-

Add a comment
Know the answer?
Add Answer to:
pls help, idk whats wrong with this Add the reverse() method which reverses the content of...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Add reverse() method which reverses the content of array without using additional array. rotate(k) method which...

    Add reverse() method which reverses the content of array without using additional array. rotate(k) method which rotates left the content of array without using additional array by k elements. import java.util.*; * Implementation of the ADT List using a fixed-length array. * * if insert is successful returns 1, otherwise 0; * for successful insertion: * list should not be full and p should be valid. * * if delete is successful returns 1, otherwise 0; * for successful deletion:...

  • Add the following method to xxxxxp3: // deletes x from sorted list k if exist, k...

    Add the following method to xxxxxp3: // deletes x from sorted list k if exist, k = 0, 1, 2 private void delete(x, k) // returns position of x in sorted list k if exist otherwise, -1. k = 0, 1, 2 private int search(x, k) import java.util.Scanner; class xxxxxp3{ private node[] head = new node[3]; private class node{ int num; node link; node(int x){ num=x; link = null; } } public void prtlst(int k){ System.out.printf("\nContents of List-%d:",k); for(node cur...

  • Fix the errors in C code #include <stdio.h> #include <stdlib.h> void insertAt(int *, int); void Delete(int...

    Fix the errors in C code #include <stdio.h> #include <stdlib.h> void insertAt(int *, int); void Delete(int *); void replaceAt(int *, int, int); int isEmpty(int *, int); int isFull(int *, int); void removeAt(int *, int); void printList(int *, int); int main() { int *a; int arraySize=0,l=0,loc=0; int choice; while(1) { printf("\n Main Menu"); printf("\n 1.Create list\n 2.Insert element at particular position\n 3.Delete list.\n4. Remove an element at given position \n 5.Replace an element at given position\n 6. Check the size of...

  • Hi I need some help on this lab. The world depends on its successfull compilation. /*...

    Hi I need some help on this lab. The world depends on its successfull compilation. /* Lab5.java Arrays, File input and methods Read the comments and insert your code where indicated. Do not add/modify any output statements */ import java.io.*; import java.util.*; public class Lab5 { public static void main (String[] args) throws Exception { final int ARRAY_MAX = 30; // "args" is the list of tokens you put after "java Project3" on command line if (args.length == 0 )...

  • To the HighArray class in the highArray.java, add a method called getMax() that returns the value...

    To the HighArray class in the highArray.java, add a method called getMax() that returns the value of the highest key in the array, or -1 if the array is empty. Add some code in main() to exercise this method. You can assume all the keys are positive numbers. // highArray.java class HighArray { private long[] a; private int nElems;    public HighArray(int max)    { a = new long[max];    nElems = 0; } public boolean find(long searchKey) { int...

  • Create an ArrayListReview class with one generic type to do the following • Creates an array...

    Create an ArrayListReview class with one generic type to do the following • Creates an array list filled with the generic type of the ArrayListReview class, and inserts new elements into the specified location index-i in the list. (5 points) • Create a method inside the class to implement the calculation of Fibonacci numbers. Use System.nanoTime to find out how much time it takes to get fab(50). Create a method inside the class to check if an array list is...

  • Doubly Linked List The assignment is to modify the below code in any way (like changing the method of a function). Time...

    Doubly Linked List The assignment is to modify the below code in any way (like changing the method of a function). Time complexity is omitted. Any methods/functions below could be changed into something different. I was thinking of changing the method of getting size of list and maybe change from numbers to letters for nodes. import java.util.Scanner; /* Class Node */ class Node { protected int data; protected Node next, prev; /* Constructor */ public Node() { next = null;...

  • Our 1st new array operation/method is remove. Implement as follows: public static boolean remove( int[] arr,...

    Our 1st new array operation/method is remove. Implement as follows: public static boolean remove( int[] arr, int count, int key ) { 1: find the index of the first occurance of key. By first occurance we mean lowest index that contains this value. hint: copy the indexOf() method from Lab#3 into the bottom of this project file and call it from inside this remove method. The you will have the index of the value to remove from the array 2:...

  • 2. Use hashing (solve_with_Hash(int[] array, int k)) Initialize a counter variable to O: Insert a...

    2. Use hashing (solve_with_Hash(int[] array, int k)) Initialize a counter variable to O: Insert all elements of array in a hashtable For every element in array: counter0 a. b. c. .Look for array[i] . Look for array [幻 + k in the hash map, if found then increment counter. -k in the hash map, if found then increment counter. Remove arrayli] from hash table. d. return counter For example: Input : array[] {1, 5, 3, 4, 2), k 3 Output:...

  • Develop a Generic String List (GSL). NOTE: I have done this lab but someting is wrong...

    Develop a Generic String List (GSL). NOTE: I have done this lab but someting is wrong here is what i was told that was needed. Ill provide my code at the very end. Here is what is missing : Here is my code: public class GSL { private String arr[]; private int size; public GSL() {     arr = new String[10];     size = 0; } public int size() {     return size; } public void add(String value) {    ...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT