I am trying to add a reverse linked list back to a linked list from an array.
public void reverse(){
//Calling function to take a linked list and put it inside an array
int[] myArray = this.toArray();
//Populate list using array
for (int i= 0; i < myArray.length; i++){
this.addHead(myArray[i]);
}
System.out.println(this.toString());
}
Here is my method this works fine but it only set the linked list to the last index and stops.
EX.
[1,7,7,6]
lS.reverse()
=> [6]
Here is the to array function
//Return int array of list values
public int[] toArray(){
//Creating a array of the size of linkedList
//New copy of head
int f[] = new int[this.size()];
Node newHead = head;
int arrayIndex = 0;
while(newHead != null){
//Set the current Index to the data at head location
f[arrayIndex] = newHead.data();
//Moves the head to next postion
newHead = newHead.next();
//Increment index
arrayIndex = arrayIndex + 1;
}
return f;
}
The result I am looking to acheive is after reverse() is called I will get from
[1,7,7,6]
To A linked list
6,7,7,1
Don't know what you are trying to achieve, but if the initial list is given, there is no need for an array conversion. You can implement something along these lines:
public <T> List<T> reverseList( List<T> list )
{
List<T> newList = new ArrayList<T>();
for( int i = 0; i < list.size(); i++ )
{
newList.add( list.get( list.size() - ( i + 1 ) ) );
}
return newList;
}
If arrays are absolutely needed for some reason, you can use this analogously. Create an array, fill up by reversing index order.
Related
I have a problem comparing the numbers inside a list so that it does not repeat using Random. I wanted the numbers to be random, but only those that are not on the list can be added.
Here is my code:
private void addToListNumber() {
int randomPosition = new Random().nextInt(5);
int maxPosition = 5;
if (list.size() < 1) {
list.add(1);
addToListNumber();
} else if (list.size() < maxPosition) {
for (Integer integer : list) {
if (integer == randomPosition) {
addToListNumber();
}
}
list.add(randomPosition);
addToListNumber();
} else {
for (Integer integer : list) {
System.out.println(integer);
}
}
}
The numbers are repeated.
If I understand correctly your question, you're trying to build a list of 5 integers, in a random order.
A simple way to get there is to generate a list of ordered numbers and then randomly swap them.
First create your list of ordered numbers.
public List<Integer> createOrderedList(int size) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < size; i++) {
list.add(i);
}
return list;
}
Then create a method that swaps two elements in the list, given their indexes.
public void swap(List<Integer> list, int i, int j) {
Integer hold = list.get(i);
list.set(i, list.get(j));
list.set(j, hold);
}
Last, create a method that mixes all of them.
public void mix(List<Integer> list) {
Random random = new Random();
for (int i = 0; i < list.size(); i++) {
swap(list, i, random.nextInt(list.size()));
}
}
Call the methods in this order:
List<Integer> list = createOrderedList(5);
mix(list);
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
This is happening because of the recursive call addToListNumber(). To make it simple and short let me assume maxPosition = 3
At first you add 1 to the list. Then suppose randomPosition = 2 and you add 2 to the list and call addToListNumber(). Now suppose randomPosition = 1, then you call addToListNumber() again on comparing integer == randomPosition (you have compared only the first element here and it matched)
Now let randomPosition = 3 and 3 be inserted. Since, this is a recursive call, on returning to addToListNumber() which was invoked for randomPosition = 1 (in the previous case), the list is not over (the list has {1,2,3}) here and only the first element has been compared. At the end of the loop it inserts 1 again and your list becomes {1,2,3,1} hence duplicates.
How can I find the elements of a 2-D List in Java?
I have a function that has a parameter of List<List<Integer>> and I want to know how to find the rows and columns of this List.
If you take like
List<List<Integer>> obj
Then you can access like
obj.get(current_row).get(current_column);
You have asked for help getting the "rows" and "columns" from a List<List<Integer>> parameter.
The get the "rows", it's pretty straightforward:
List<List<Integer>> table;
for (List<Integer> row : table) {
// do something with 'row'
}
Columns are not straightforward though:
List<List<Integer>> table; // assumed to not be empty
int columnCount = table.get(0).size();
for (int columnNumber = 0; i < columnCount; columnNumber++) {
List<Integer> column = new ArrayList<>();
for (List<Integer> row : table) {
column.add(row.get(columnNumber));
}
// do something with 'column'
}
To save on reprocessing for each access to column data, you could store the columns in a List<List<Integer>> variable, then access those similarly to accessing rows.
The List api defines an api get
List<List<Integer>> listOfLists;
// get, then get again
Integer integer = listOfLists.get(row).get(column);
The first "get" in the chain returns a List<Interger>, so you get again to get the integer
Just like you would do if you had an int[][] except that you would need to use the retrieval methods of the lists.
The easiest way is to use the fact that Lists implement the Iterable interface.
So you could
// create some data
List<List<Integer>> listofLists = new ArrayList<>();
for (int i = 0; i < 4; i++) {
listofLists.add(Arrays.asList(1 * i, 2 * i, 3 * i));
}
Display it
for (List<Integer> list : listofLists) {
System.out.println(list); // prints out each row.
}
Say you wanted to convert it to an int[][] array interating thru all individual elements.
int[][] ints = new int[listofLists.size()][];
for (int i = 0; i < listofLists.size(); i++) {
// get each list in succession
List<Integer> list = listofLists.get(i);
// allocate the columns array to the size
ints[i] = new int[list.size()];
// copy each item over individually
for (int k = 0; k < list.size(); k++) {
ints[i][k] = list.get(k);
}
}
// print the arrays
for (int[] i : ints) {
System.out.println(Arrays.toString(i));
}
I am having issues trying to figure out how to display all elements in a LinkedList. I could solve this by having an arraylist to track the index of every element, however I would want to solve this without the use of arraylist or arrays.
The following is what I currently have,
public void displayItems()
{
ArrayList<Node> links = new ArrayList<Node>();
links.add(head);
for (int x = 0; x < count; x++)
{
links.add(links.get(x).getLink());
System.out.println(links.get(x).getData());
}
is there a way to display all elements, in a similar method as mentioned above but without the need for arrays or ListIterator?
A few examples how to loop through LinkedList in Java (including one you don't like - using Iterator):
LinkedList<Node> links = new LinkedList<Node>();
links.add(firstNode);
links.add(secondNode);
links.add(thirdNode);
/* For loop */
for(int i = 0; i < links.size(); i++) {
System.out.println(links.get(i).getLink());
}
/* For-each loop */
for(Node node: links) {
System.out.println(node.getLink());
}
/* While Loop*/
int i = 0;
while (links.size() > i) {
System.out.println(links.get(i++).getLink());
}
/* Iterator */
Iterator<Node> it = links.iterator();
while (it.hasNext()) {
System.out.println(it.next().getLink());
}
You can use an integer as a global variable, while inserting data into Linked List increment this variable.
Write a method in LinkedList class with parameter position. Here loop upto the position, get the data and return the same.
This question already has answers here:
How to add an element at the end of an array?
(6 answers)
Closed 6 years ago.
Hello i need to manually implement an arraylist.add() method using nothing but arrays and an array copy method but im having trouble doing it . The specification of the method is that the method inserts an element at a specified position and shifts any of the elements currently in the position to the right and add one to the indices expanding the size of the array by one so all elements fit . Someone please help .
private Object [] list;
final int maxObjects = 100;
public ListOfObjects()
{
list= new Object[maxObjects];
}
public ListOfObjects(Object[]o)
{
list= o;
}
public void add(Object element,int index)
{
Object[] newData = new Object[list.length+1];
for(int i =0; i < index; i++)
{
newData[i] = list[i];
newData[list] = element;
}
for(int i = index; i < list.length; i++)
{
newData[i+1] = list[i];
}
}
Adding an element to an index of an Object array,
Object[] myObjects;
public static void addObject(Object obj, int index) {
// Assuming you want something in your empty array
if(myObjects == null) {
myObjects = new Object[] { obj };
return;
}
ArrayList<Object> temp = new ArrayList<Object>();
for(int i = 0; i < myObjects.length; i++) {
if(i == index)
temp.add(obj);
temp.add(myObjects[i]);
}
myObjects = temp.toArray(new Object[temp.size()]);
}
The javadoc of System.arrayCopy speaks specifically to the case of the src and dest being the same array:
If the src and dest arguments refer to the same array object, then the
copying is performed as if the components at positions srcPos through
srcPos+length-1 were first copied to a temporary array with length
components and then the contents of the temporary array were copied
into positions destPos through destPos+length-1 of the destination
array.
If your backing list is of sufficient size, then you simply need to use arrayCopy to move the affected indexes over 1.
//shift everything after the index over
System.arrayCopy(list, index, list, index + 1, list.length - index);
//place new value in index
list[index] = element;
Otherwise you need to create a new array, then use arrayCopy to copy everything before the inserting index.
Object[] newList = new Object[calcSize()];
//first copy everything before index if index is not 0
if (index > 0)
{
System.arrayCopy(list, 0, newList, 0, index);
}
newList[index] = element;
System.arrayCopy(list, index, newList, index+1, list.length - index);
You logic looks wrong to me. You should do something like -
Object[] newData = new Object[list.length+1];
for(int i =0; i < index; i++)
{
newData[i] = list[i];
}
newData[index] = element;
for(int i = index; i < list.length; i++)
{
newData[i+1] = list[i];
}
This solution takes advantage of the ArrayList iterator, which returns objects in the proper sequence:
ArrayList<Object> elementInserter(ArrayList<Object> inArray, Object element, int index){
ArrayList<Object> outArray = new ArrayList<Object>(inArray.size() + 1);
outArray.addAll(inArray.subList(0, index));
outArray.add(element);
outArray.addAll(inArray.subList(index, inArray.size()));
return outArray;
}
Write a method deleteElement which takes as input an int[] and an int target and deletes all occurrences of target from the array. The method should return the newint[]
. Question to consider:
Why is it that we have to return an array and can't simply change the input parameter array?
public class warm5{
public static void main(String[] args){
int[] array1= {1,2,2,3,4,5,2};
int target1 = 2;
deleteElement(array1,target1);
public static int[] deleteElement(int[] array, int target){
for(int i = 0, i<array.length, i++){
if(array1[i] == target){
}
}
}
}
}
Here is what i wrote, im not sure how to continue it to remove the 2's in the array.
please help!
You can't delete elements from an array, by definition they're of fixed size. What you can do is create a new array, copy all the elements from the old array except the ones that you intend to delete and return the new array. Or, use an ArrayList, which has operations that allow removing elements:
public E remove(int index)
public boolean remove(Object o)
public boolean removeAll(Collection<?> c)
protected void removeRange(int fromIndex, int toIndex)
First, iterate through your array and figure out how many of your target element are present.
Once you know that, you know the size of your new array. As Oscar mentions, you can't "remove" from an array, you just make a new array without the elements you don't want in it.
int targetCount = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == target) {
targetCount++;
}
}
Now you know how many items will be in your new array: array.length-targetCount.
int[] newArray = new int[array.length-targetCount];
int newArrayIdx = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] != target) {
newArray[newArrayIdx] = target;
newArrayIdx++;
}
}
Here we iterate through the old array and check each element to see if it's our target. If it's not, we add it to the new array. We have to keep track of our old array's index and our new array's index independently or we may risk trying to assign an index outside of the array bounds.
This is a common interview question. In the solution presented by Oscar you do not know what will be the size of the new array. So the solution does not work or is memory inefficient.
Trick is to loop over the array and at any time when you encounter an element equal to the given element you put that element towards the end of the array and swap it with the element that was there at the end position. By doing this you are collecting all occurrences of given element at the end of the array.
Here is a working logic
deleteElement(int[] given, int elem) {
int endIdx = array.length - 1;
for(int idx = 0; idx <= endIdx; idx++) {
if(given[idx] == elem) {
//swap idx with endIdx
int tmp = given[endIdx];
given[endIdx] = given[idx];
given[idx] = tmp;
endIdx--;
}
}
return Arrays.copyOfRange(given, 0, endIdx);
}