I want to write function Print Reverse of LinkedList in Java. I write like this but it doesn't work. Compiler warn that NullPointerException.
void ReversePrint(Node head) {
int[] array = null;
int i = 0;
Node tmp;
for (tmp = head; tmp != null; tmp = tmp.next) {
array[i] = tmp.data;
i++;
}
for(int j = i; j >= 0; j--){
System.out.println(array[j]);
}
}
You get the NullPointerException because the variable array is null:
int[] array = null;
You need to initialize it first with a value before you are using it here:
array[i] = tmp.data;
For example with a statement like this:
int[] array = new int[size];
Where size should probably be the size of your LinkedList. If you, for whatever reason, don't know the size, you can use the class ArrayList which realizes arrays with dynamic size (it guesses a size and if your exceeding it, it will re-allocate a bigger array and copy everything over and so on).
Here's a version using said ArrayList:
// Method names should start with a lower-case letter
void reversePrint(Node head) {
// Initialize an empty ArrayList
ArrayList<Integer> dataList = new ArrayList<>();
int i = 0;
Node tmp;
for (tmp = head; tmp != null; tmp = tmp.next) {
// Set the element at position i of the ArrayList
dataList.set(i, tmp.data);
i++;
}
// See next comment
i--;
for(int j = i; j >= 0; j--){
// Get the element at position j of ArrayList and print it
System.out.println(dataList.get(j));
}
}
Note that you will also encounter an IndexOutOfBoundException since your i is 1 to big when reaching the print-loop. This is because you increased it also in the last iteration of your first loop:
// Suppose last iteration, i is (list.size() - 1) then
for (tmp = head; tmp != null; tmp = tmp.next) {
array[i] = tmp.data;
// i is now list.size()
i++;
}
You need one i-- between the loops or int j = i - 1 in your loop initialization.
If you are realizing a doubly-linked list instead of only a single-linked list then note that you do not need to story values in an array first. You then can directly print the values by starting at tail and following tmp.prev pointers.
The simplest way to do this is with a recursive method:
void ReversePrint(Node node) {
if (node != null) {
ReversePrint(node.next);
System.out.println(node.data);
}
}
Related
This question already has answers here:
How do I remove objects from an array in Java?
(20 answers)
Closed 1 year ago.
I am currently working on a delete method on a fixed array. Here is the implementation of the delete method below. What it does in the first for-loop is it gets the index if the data has a match on the array. For the next if and for-loop, its supposed to move the contents of the index if for example, the element deleted is at the 2nd or 3rd index of an array of length 5. It returns true, if the element has been successfully deleted in the array and false if not.
public boolean delete(E data) {
int index = -1;
int size = list.length;
for (int i = 0; i < list.length; i++) { // for getting what index in the array
if (data == list[i]) { // is the element in if there is a match
index = i;
}
}
if (index > -1) { // for swapping the index when
final int newArraySize; // the element is deleted in the
if ((newArraySize = size - 1) > index) { // between first-2nd to the last
for (int x = 0; x < list.length; x++) { // index in the array.
if (list[x] == null) {
for (int y = 0; y < x; y++) {
// move items
list[y] = list[y+1];
}
}
}
}
list[size = newArraySize] = null;
return true;
}
return false;
}
When I try running it, it doesn't delete the element. I'm having problems with the implementation of the swapping index part. I need help.
Your solution has time complexity of O(nxn). Instead you can start from the index of element being removed and swap all elements from index of element being removed.
for (int i = index; i < list.length - 1; i++) {
list[i] = list[i + 1];
}
But above solution might retain same size of the array and have repeat elements.
I will suggest using two array solutions, it adds bit of space complexity but effectively removes element and reduces the array size. Also you need to return this updated array.
int[] copy = new int[list.length - 1];
for (int i = 0, j = 0; i < list.length; i++) {
if (i != index) {
copy[j++] = list[i];
}
}
The job of this method is to remove the value toRemove from the array. The remaining elements should just be shifted toward the beginning of the array. (The array's size will not change.) Since the array will now have one fewer element, the position of the last element should just be filled with 0. If there is more than one occurrence of toRemove in the array, only the first occurrence should be removed. The method has no return value, and if the array has no elements, it should just have no effect.
The solution:
public static void remove(int[] arr, int toRemove) {
boolean done = false;
int position = 0;
for(int pos = 0; pos < arr.length; pos++) {
if(!done && arr[pos] == toRemove) {
done = true;
position = pos;
}
if(done) {
for(int i = position + 1; i < arr.length; i++) {
arr[i - 1] = arr[i];
}
arr[arr.length -1] = 0;
}
}
}
I am not following how this algorithm works. The use of boolean confuses me, I feel I don't fully understand what the primitive data type does, I know that it holds two things either true or false, and false by default. But what does that really mean? I don't understand boolean.
I understand why would want an int placeholder for the index of where the toRemove value was found. I understand we would want to use a for-loop to iterate one-by-one the indices and their respective values and pinpoint where exactly toRemove is found. I understand we would want a check point conditional to see if at some arbitrary index the toRemove value exists, andd therefore:
if(arr[pos] = toRemove) // then bingo we've found him
I don't understand the boolean !done, booleans confuse me.
why after this check point is there done = true? and then after that another check if(done)? and why another for loop for(int i = position + 1; i < arr.length; i++) and after that for loop the line arr[i - 1] = arr[i];? and finally at the end arr[arr.length-1] = 0 and position = pos;
I understand when we want to access a particular indicies value we write variablenameOfArr then the [] and put it inside the box. I am having difficulty putting this all together.
Thank you
In this case, the boolean done seems to control whether a value has already been removed or not. It begins the algorithm as false, as nothing has been removed yet.
The first if statement tests to see if the value of done is false. In if statements, instead of saying if(done == false), this can be simplified to if(!done). So, this if statement simply tests to see if a value has been found yet or not.
done is then set to true once a value has been removed, so that no future values will be removed.
Finally, the second if statement tests to see if a value has been removed or not. Like the first if statement, if(done == true) can be simplified to if(done).
I hope this helps, comment with any further questions if they arise.
public static void remove(int[] arr, int toRemove) {
boolean done = false; //This boolean is used to determine when the element has been found
int position = 0;
for(int pos = 0; pos < arr.length; pos++) { //Iterating through the array
//if we aren't already done, (!done = NOT DONE) and we have found the position to remove, then enter this logic
if(!done && arr[pos] == toRemove) {
done = true; //since we found the position to remove, set done to true
position = pos; //Save the index of the one that was removed
}
if(done) { //if we are done, enter this logic
//This loop starts above the index where removed, and iterates to the top
for(int i = position + 1; i < arr.length; i++) {
arr[i - 1] = arr[i]; //This shifts each element down one
}
arr[arr.length -1] = 0; //This sets the empty slot at the top of the array to 0
}
}
}
The boolean is indeed not necessary since it is always true when if(!done && arr[pos] == toRemove) is true.
Besides, it makes no sense to go on the outer loop when you have removed an element as 1) the state of the array is nice : the inner loop has shifted the elements after the removed element to their left and 2) you cannot perform two removals.
By the way the position variable is also not required. You can use the pos variable directly as it is read only used.
This code :
for(int pos = 0; pos < arr.length; pos++) {
if(!done && arr[pos] == toRemove) {
done = true;
position = pos;
}
if(done) {
for(int i = position + 1; i < arr.length; i++) {
arr[i - 1] = arr[i];
}
arr[arr.length -1] = 0;
}
}
could be replaced by this without using the boolean and you could also exist the method after the array elements were shifted :
for(int pos = 0; pos < arr.length; pos++) {
if(arr[pos] == toRemove) {
for(int i = pos + 1; i < arr.length; i++) {
arr[i - 1] = arr[i];
}
arr[arr.length -1] = 0;
return;
}
}
I'm making a class that deletes an element at a specific position in an Integer array. It runs perfectly the first 2 times, but then for some reason it decides that the ArrayIndexOutOfBoundsException should be thrown.
my code:
public class Arraydeletion {
public static int[] delete (int[] a, int delValPos){
int[] newArray = new int[a.length-1];
for (int i = 0; i < newArray.length; i++) {
if(a[i]!=a[delValPos]){ //<--- ArrayIndexOutOfBoundsException points here
newArray[i] = a[i];
}
else if(a[i] == a[delValPos]){
newArray[i] = a[delValPos+=1];
}
}
return newArray;
}
}
You never check that delValPos is a valid index within the input array a. Your method must validate it before doing anything else, and throw an exception if an invalid delValPos is supplied.
Working code would look like this :
public class Arraydeletion {
public static int[] delete (int[] a, int delValPos){
if (delValPos < 0 || delValPos >= a.length)
throw new SomeException(); // TODO decide which exception to throw
int[] newArray = new int[a.length-1];
int index = 0;
for (int i = 0; i < a.length; i++) {
if (i!=delValPos) {
newArray[index] = a[i];
index++;
}
}
return newArray;
}
}
This makes the code much simpler. It copies all the elements except a[delValPos] to the output array. Note that you can't use the same index i for reading elements from the input array and writing elements to the output array, because after you pass the deleted element, each i'th element in the input array would be written to the (i-1)'th place in the output array.
I tested your code and i retrieve outOfBoundException only if delValPos == a.length, so you can check this before loop.
However your code is pretty strange, it seems you want to clone an array except for one element in a certain position, if so this will work better:
public static int[] delete (int[] a, int delValPos){
int delValPos = 0;
int[] a = {1,2,3,4,5,6,7,8,9};
int[] newA = new int[a.length - 1];
if(a.length > delValPos) {
for(int i = 0 ; i < newA.length ; i++) {
if(delValPos < i && delValPos != 0) {
newA[i] = a[i];
}
else
newA[i] = a[i + 1];
}
}
return newA;
}
ok I have this code that someone helped with me
public void add(int index, E element)
if (index < 0 || index >= mList.length){
throw new IndexOutOfBoundsException(); // check if index is ok.
}
Object[] temp = new Object[mList.length + 1]; // create the new array into temp.
for (int i = 0, j = 0; j < temp.length; ++i, ++j){ // loop into the array by comparing the first array to the second array's index i&j
if ( i == index ) { // check if i is valid
temp[index] = element; // insert element into the array
--i; // decrement original array to cancel out j temp array
} else {
temp[j] = mList[i]; //
}
}
mList = temp;
}
Now I need to
public E remove(int index)
Do I need to create a temp array again?
I know there are two arrays, do I just do a for loop on the current array which is temp?
If you want to do it in a way similar to your add, then yes, you need a temp array.
public E remove(int index) {
Object[] temp = new Object[mList.length + 1];
for (int i = 0; j < mList.length; ++i) {
if(i<index) temp[i]=mList[i];
if(i>index) temp[i-1]=mList[i];
//N.B. not added if i == index
}
mList = temp;
}
To sum it up, you don't remove the element from the array, you just don't add it to the new one.
If you want a better solution, you should take a look at System.arraycopy() and Arrays.copyOf(). Give it a try and if you have difficulties don't shy away from asking.
If you are not forced to use arrays, I'd suggest you use Collections. For instance a List would suit your needs very well.
I have to write a method that takes an array of ints that is already sorted in numerical order then remove all the duplicate numbers and return an array of just the numbers that have no duplicates. That array must then be printed out so I can't have any null pointer exceptions. The method has to be in O(n) time, can't use vectors or hashes. This is what I have so far but it only has the first couple numbers in order without duplicates and then just puts the duplicates in the back of the array. I can't create a temporary array because it gives me null pointer exceptions.
public static int[] noDups(int[] myArray) {
int j = 0;
for (int i = 1; i < myArray.length; i++) {
if (myArray[i] != myArray[j]) {
j++;
myArray[j] = myArray[i];
}
}
return myArray;
}
Since this seems to be homework I don't want to give you the exact code, but here's what to do:
Do a first run through of the array to see how many duplicates there are
Create a new array of size (oldSize - duplicates)
Do another run through of the array to put the unique values in the new array
Since the array is sorted, you can just check if array[n] == array[n+1]. If not, then it isn't a duplicate. Be careful about your array bounds when checking n+1.
edit: because this involves two run throughs it will run in O(2n) -> O(n) time.
Tested and works (assuming the array is ordered already)
public static int[] noDups(int[] myArray) {
int dups = 0; // represents number of duplicate numbers
for (int i = 1; i < myArray.length; i++)
{
// if number in array after current number in array is the same
if (myArray[i] == myArray[i - 1])
dups++; // add one to number of duplicates
}
// create return array (with no duplicates)
// and subtract the number of duplicates from the original size (no NPEs)
int[] returnArray = new int[myArray.length - dups];
returnArray[0] = myArray[0]; // set the first positions equal to each other
// because it's not iterated over in the loop
int count = 1; // element count for the return array
for (int i = 1; i < myArray.length; i++)
{
// if current number in original array is not the same as the one before
if (myArray[i] != myArray[i-1])
{
returnArray[count] = myArray[i]; // add the number to the return array
count++; // continue to next element in the return array
}
}
return returnArray; // return the ordered, unique array
}
My previous answer to this problem with used an Integer List.
Not creating a new array will surely result in nulls all over the initial array. Therefore create a new array for storing the unique values from the initial array.
How do you check for unique values? Here's the pseudo code
uniq = null
loop(1..arraysize)
if (array[current] == uniq) skip
else store array[current] in next free index of new array; uniq = array[current]
end loop
Also as others mentioned get the array size by initial scan of array
uniq = null
count = 0
loop(1..arraysize)
if (array[current] == uniq) skip
else uniq = array[current] and count++
end loop
create new array of size count
public static int[] findDups(int[] myArray) {
int numOfDups = 0;
for (int i = 0; i < myArray.length-1; i++) {
if (myArray[i] == myArray[i+1]) {
numOfDups++;
}
}
int[] noDupArray = new int[myArray.length-numOfDups];
int last = 0;
int x = 0;
for (int i = 0; i < myArray.length; i++) {
if(last!=myArray[i]) {
last = myArray[i];
noDupArray[x++] = last;
}
}
return noDupArray;
}
public int[] noDups(int[] arr){
int j = 0;
// copy the items without the dups to res
int[] res = new int[arr.length];
for(int i=0; i<arr.length-2; i++){
if(arr[i] != arr[i+1]){
res[j] = arr[i];
j++;
}
}
// copy the last element
res[j]=arr[arr.length-1];
j++;
// now move the result into a compact array (exact size)
int[] ans = new int[j];
for(int i=0; i<j; i++){
ans[i] = res[i];
}
return ans;
}
First loop is O(n) and so is the second loop - which totals in O(n) as requested.