Method will not replace last element in a list - java

I have a method to replace elements in a linked list. It was working fine however I noticed that the last element in the list does not get replaced. I wanted to know where am I going wrong?
public class ListOfNVersion03PartB
{
private int thisNumber; // the number stored in this node
private ListOfNVersion03PartB next; // forms a linked list of objects
private final int nodeID; // a unique ID for each object in the list
private static int nodeCount = 0; // the number of list objects that have been created
public ListOfNVersion03PartB(int num)
{
thisNumber = num;
next = null;
++nodeCount;
nodeID = nodeCount;
}
public int replaceOnce(int replaceThis, int withThis)
{
int count = 0;
if( (next!= null) && (thisNumber == replaceThis) ){
thisNumber= withThis;
return count =1;
}
if( (next!= null) && (thisNumber != replaceThis) ){
return next.replaceOnce(replaceThis,withThis);
}
else
return count;
}

Try to loop over the node and compare with the value and replace if you found a node with replaceThis value
public int replaceOnce(int replaceThis, int withThis) {
ListOfNVersion03PartB current = this;
int count = 0;
while (current != null) {
if (current.thisNumber == replaceThis) {
current.thisNumber = withThis;
count++;
}
current = current.next;
}
return count;
}

Related

trying to do a replace method in linked list but program replaces only the first element

My current code only replaces the first element of the linked list. I am trying to create a replace method with two parameters but failing. My current logic shows that I am trying to replace the element with my new input but I am assuming I am failing to traverse through the list as only the first one gets replaced.
public class ListOfNVersion03PartA
{
private int thisNumber; // the number stored in this node
private ListOfNVersion03PartA next; // forms a linked list of objects
private int []list;
private final int nodeID; // a unique ID for each object in the list
private static int nodeCount = 0; // the number of list objects that have been created
/**
* #param num the value to be stored in this object
*/
public ListOfNVersion03PartA(int num)
{
thisNumber = num;
next = null;
++nodeCount;
nodeID = nodeCount;
}
public ListOfNVersion03PartA(int [] num)
{
this(num[0]); // in this context, "this" invokes the other constructor
list = new int[num.length];
for (int i=1 ; i<num.length ; ++i)
{
insertLast(num[i]);
}
}
public int replaceAll(int replaceThis, int withThis)
{
int count = 0;
int x = 0;
for ( int i=0 ; i < nodeCount; ++i)
{
if ( thisNumber == replaceThis )
{
thisNumber = x;
x = withThis;
++count;
}
}
return count;
}
Once you've evaluated the current node (aka this), then you should perform the evaluation of the next node until there are no more nodes to evaluate. Here's an example using your current code:
public int replaceAll(int replaceThis, int withThis) {
int result = 0;
if (thisNumer == replaceThis) {
thisNumber = withThis;
result = 1;
}
if (next != null) {
result += next.replaceAll(replaceThis, withThis);
}
return result;
}

How can I fix my code to give the correct output instead of giving nothing?

When i run my code, i get nothing as my output. I suspect my code stops on this method:
public void deleteAt(int position)
{
if (position >= 0)
{
for (int i = position; i < theArray.length; i++)
{
theArray[i] = theArray[i + 1];
}
}
}
I think it stops at the above method because this code:
public int positionOf(char value)
{
//Search the list to find the value, if found return the position, if not, return -1
for (int i = 0; i < size(); i ++)
{
if (theArray[i] == value)
{
return i;
}
}
return -1;
}
only returns -1. If i remove the return -1; then Java thinks that there is an error because there is no return statment. I tried adding an else, but i still get the same error.
This is the whole code:
/** The interface for our List (Abstract Data Type) */
interface IList {
/** Adds the given value to the end of the list */
void append(char value);
/** Adds the given value to the beginning of the list */
void prepend(char value);
/** Deletes the container at the given position (a container holds a value) */
void deleteAt(int position);
/** Returns the number of values currently in our list */
int size();
/** Retrieves the value at the given position */
char getValueAt(int position);
/** Searches for the FIRST occurence of a given value in our list.
* If found, it returns the position of that value.
* If not found, it returns -1 */
int positionOf(char value);
}
/** Array implementation of our List */
class ListAsArray implements IList {
// initialize array to a size of 30 elements
// this will prevent the need to resize our array
char[] theArray = new char[30];
public void append(char value)
{
//Count until you find a place in the array that is empty, then insert
for (int i = 0; i < theArray.length; i ++)
{
if (theArray[i] == 0)
{
theArray[i] = value;
}
}
}
public void prepend(char value)
{
//Count until you find a empty value
for (int i = 0; i < theArray.length; i ++)
{
if (theArray[i] == 0)
{
//Once you find the empty value move everything over
for(int j = theArray.length; j != 0; j--)
{
theArray[i] = theArray[i + 1];
}
}
}
//Finally you want to actually add in the number in the first position
theArray[0] = value;
}
public void deleteAt(int position)
{
if (position >= 0)
{
for (int i = position; i < theArray.length; i++)
{
theArray[i] = theArray[i + 1];
}
}
}
public int size()
{
//Count until you find a place in the array that is empty, then return the number
int count = 0;
for (int i = 0; i < theArray.length; i ++)
{
if (theArray[i] == 0)
{
return count;
}
count ++;
}
return 0;
}
public char getValueAt(int position)
{
return theArray[position];
}
public int positionOf(char value)
{
//Search the list to find the value, if found return the position, if not, return -1
for (int i = 0; i < size(); i ++)
{
if (theArray[i] == value)
{
return i;
}
}
return -1;
}
}
/** Singly Linked List implementation of our List */
class ListAsLinkedList implements IList {
//Point to first node and second node
private Node head;
private Node tail;
//Constructor sets head and tail to null
public void LinkedList()
{
head = null;
tail = null;
}
public void append(char value)
{
//Wrap the data in a node
Node temp = new Node(value);
//Make this the first node if no other nodes
if (tail == null)
{
//Set tail to new node
tail = temp;
//Set head to new node
head = temp;
}
else
{
//Set new node to be after current end
tail.setNext(temp);
//Set as new tail
tail = temp;
}
}
public void prepend(char value)
{
//Wrap the data in a node
Node temp = new Node(value);
//Make this the first node if no other nodes
if (tail == null)
{
//Set tail to new node
tail = temp;
//Set head to new node
head = temp;
}
else
{
temp.next = head;
head = temp;
}
}
public void deleteAt(int position)
{
//Make the head node the next node if its the first one
if(position == 0)
{
head=head.next;
}
//If that wasn't the case...
Node current = head;
for(int i = 0; i < position-1; i++)
{
current = current.next;
}
current.next = current.next.next;
if(current.getNext() == null)
{
tail = current;
}
}
public int size()
{
Node temp = head;
for (int i = 0; i != 103; i++)
{
if (temp == tail)
{
return i;
}
}
return 0;
}
public char getValueAt(int position)
{
Node temp=head;
for(int i=0; i < position; i++)
{
temp=temp.next;
}
return temp.data;
}
public int positionOf(char value)
{
//Start at the beginning
int position = 0;
Node current = head;
//Look until we find target data
while (current.getData() != value)
{
//Move to next node
current = current.getNext();
//Increment position
position++;
}
//return position found
return position;
}
}
/** A singly linked list node for our singly linked list */
class Node {
//The node data and link to next node
public char data;
public Node next;
//Constructor
public Node(char data)
{
this.data = data;
this.next = null;
}
//Accessor
public char getData()
{
return data;
}
//Accessor
public Node getNext()
{
return next;
}
//Mutator
public void setData(char data)
{
this.data = data;
}
//Mutator
public void setNext(Node next)
{
this.next = next;
}
}
This is main:
/** contains our entry point */
public class Main {
/** entry point - DO NOT CHANGE the pre-existing code below */
public static void main(String[] args) {
int[] numbers = {105,116,112,115,65,58,47,47,116,105,110,121,88,117,114,108,46,99,111,109,47};
int[] numbers2 = {97,59,111,53,33,111,106,42,50};
int[] numbers3 = {116,104,32,111,116,32,111,71};
/// List as an Array
IList array = new ListAsArray();
// add values
for(int num : numbers) {
array.append((char)num);
}
for(int num : numbers3) {
array.prepend((char)num);
}
// delete some values
int position;
position = array.positionOf((char)105);
array.deleteAt(position);
position = array.positionOf((char)65);
array.deleteAt(position);
position = array.positionOf((char)88);
array.deleteAt(position);
// print em
position = 0;
while (position < array.size()) {
System.out.print(array.getValueAt(position));
position++;
}
/// List as a Linked List
IList linkedList = new ListAsLinkedList();
// add values
for(int num : numbers2) {
linkedList.append((char)num);
}
linkedList.prepend((char)55);
linkedList.prepend((char)121);
// delete some values
position = linkedList.positionOf((char)59);
linkedList.deleteAt(position);
position = linkedList.positionOf((char)33);
linkedList.deleteAt(position);
position = linkedList.positionOf((char)42);
linkedList.deleteAt(position);
// print em
position = 0;
while (position < linkedList.size()) {
System.out.print(linkedList.getValueAt(position));
position++;
}
System.out.println();
// ???
}
}
It should be outputting a link pertaining to the next part of my assignment.
The size() method always returns 0 according to your input.
size() method as per your code doesn't give you the length of the array to iterate over. Therefore you should use array length i.e theArray.length in positionOf() method's for loop instead of size() method.

convert binary to decimal using single linked list and recursive method in java

How we can convert binary to decimal using single linked list and recursive method in java? :-s
Ex:
Input: 1->0->0->NULL
Output: 4
I can think of two ways to solve it:
1- If length of list is known:
// To find length of list
public int length(Node head) {
int count = 0;
while(head != null) {
count++;
head = head.next;
}
return count;
}
public static int convertWhenLengthIsKnown(Node head, int len) {
int sum = 0;
if(head.next != null) {
sum = convertWhenLengthIsKnown(head.next, len-1);
}
return sum + head.data * (int)Math.pow(2,len);
}
// Call this function as below:
convertWhenLengthIsKnown(head, length(head)-1);
If we don't want to calculate length, then we can have a sum variable which is globally accessible,
private static int sum = 0;
public static int convert(Node head,int i) {
if(head.next != null) {
i = convert(head.next, i);
}
sum += head.data * (int)Math.pow(2,i);
return i+1;
}
// Call this function as below:
convert(head,0);
Below is the Node class:
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
}
}
Hope It helps you.
It's a bit tricky recursively because you need to scale "earlier" values depending on the list length, simplest way seems to be to hand down the result "so far" via an additional parameter.
class Node {
int value;
Node next;
int toDecimal(int resultSoFar) {
int resultSoFar = 2 * resultSoFar + value;
return next == null ? resultSoFar : toDecimal(resultSoFar);
}
int toDecimal() {
toDecimal(0);
}
}
Try this (Without the null at the end of the list) :
public Integer binToDec(LinkedList<Integer> list){
Double size = (double) list.size();
if(size == 0D) return 0;
Integer number = list.getFirst();
list.removeFirst();
if(number != 0) return binToDec(list) + number*new Double(Math.pow(2D, size - 1)).intValue();
else return binToDec(list);
}
Be aware that it will clear the list.
As you did not tell anything about your linked list, I assume it's similar to the Node class from pbajpai21.
Without knowing the length of the chain you could with each level shift the value one position to the left.
the class for each node in the list
class Node {
int digit;
Node child;
Node(int data) {
this.digit = data;
}
public int getDigit() {
return digit;
}
public void setChild(Node child) {
this.child = child;
}
public Node getChild() {
return child;
}
}
the class for demonstration
public class Bits {
public static void main(String[] args) {
int[] ints = new int[] {1, 0, 1, 0, 1, 0};
Node parent = new Node(ints[0]);
Node root = parent;
for (int i = 1; i < ints.length; i++) {
Node child = new Node(ints[i]);
parent.setChild(child);
parent = child;
}
long value = computeValue(0, root);
System.out.println();
System.out.println("value = " + value);
}
private static long computeValue(long parentValue, Node node) {
if (node == null) {
return parentValue;
}
// only to print the current digit
System.out.print(node.getDigit());
long value = (parentValue << 1) + node.getDigit();
return computeValue(value, node.getChild());
}
}
output
101010
value = 42

thread "main" java.lang.NullPointerException, Implement three stack in a single array

The purpose of this code is to implement three stacks in a single array. I use linked node to implement stack. the elements are pushed into array one by one directly, and the elements in each stack are connected by previous pointer. the pointer is int value corresponding to index in array where the item is stored. nextAvaIndexmethod return next available index that can store new pushed item. Because there will space released in the beginning of the array after executing pop method. ifindexused < arr.lengthit will keep moving forward to store new item, while if indexusedreaches end of array, the method will search is there free space in beginning of array.
But when I run it, it throws NullPointerException, i know the meaning of this error, but I can't fix it. Thanks for your comments! Is the code correct? One more question of removal an item from int type array. I letarr[i].data = 0 to delete the item, and use statement arr[i].data == 0 to check if one space is null. But what if one space store0? Thanks for your suggestion!
public class FlexiblemultiStack {
private int[] toppoint = {-1, -1, -1};// assume number of stack ==3;
private int indexused = 0;
private stackNode[] arr;
public FlexiblemultiStack(int sizeEach, int stackNO) {
arr = new stackNode[sizeEach * stackNO]; //
}
public boolean isEmpty(int stackNum) {
return toppoint[stackNum] == 0;
}
public void push(int item, int stackNum) {
int lastIndex = toppoint[stackNum];
int nextIndex = nextAvaIndex();
if (nextIndex == -1) { // if nextIndex = -1, there is no more space!
System.out.println("There is no more space!");
} else {
toppoint[stackNum] = nextIndex;
arr[toppoint[stackNum]] = new stackNode(item, lastIndex);
indexused++;
}
}
public int pop(int stackNum) {
if (toppoint[stackNum] == -1) {
return 0;
} else {
int value = arr[toppoint[stackNum]].data;
int lastIndex = toppoint[stackNum];
toppoint[stackNum] = arr[toppoint[stackNum]].previous;
arr[lastIndex] = null;
indexused--;
return value;
}
}
public int peek(int stackNum) {
return arr[toppoint[stackNum]].data;
}
public int nextAvaIndex() {
int index = -1;
if (indexused == arr.length || arr[indexused].data != 0) {
for (int i = 0; i < arr.length; i++) {
if (arr[i].data == 0) { // error
index = i;
break;
}
}
return index;
} else {
return indexused;
}
}
public void print(int stackNum) {
while (toppoint[stackNum] != -1) {
System.out.print(arr[toppoint[stackNum]].data + "<--");
toppoint[stackNum] = arr[toppoint[stackNum]].previous;
}
}
public void printarr(){
for(int i = 0; i< arr.length;i++){
System.out.print(arr[i]);
}
}
public class stackNode { // Exception in thread "main" java.lang.NullPointerException
List item
private int previous;
private int data;
public stackNode(int StackSize) {
this.previous = -1;
}
public stackNode(int value, int prev) {
data = value;
previous = prev;
}
}
}
Exception in thread "main" java.lang.NullPointerException
at stackandqueue.FlexiblemultiStack$stackNode.access$000(FlexiblemultiStack.java:86)
at stackandqueue.FlexiblemultiStack.nextAvaIndex(FlexiblemultiStack.java:61)
at stackandqueue.FlexiblemultiStack.push(FlexiblemultiStack.java:32)
at stackandqueue.StackandQueue.main(StackandQueue.java:71)
/Users/xchen011/Library/Caches/NetBeans/8.1/executor-snippets/run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)
In the pop() method, it appears you are denoting an open index by setting the array index to null (arr[lastIndex] = null). In nextAvaIndex() you check if the index is available by examining arr[i].data. If arr[i] has been set to null by pop(), you will get the NullPointerException. To make the definition of available consistent with the check for availability, try replacing arr[indexused].data != 0 with arr[indexused] != null and if(arr[i].data == 0) with if(arr[i] == null) in the nextAvaIndex() method.
public int nextAvaIndex() {
int index = -1;
if (indexused == arr.length || arr[indexused] != null) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == null) { // error
index = i;
break;
}
}
return index;
} else {
return indexused;
}
}

Recursively find nth to last element in linked list

I'm practicing basic data structure stuff and I'm having some difficulties with recursion. I understand how to do this through iteration but all of my attempts to return the nth node from the last of a linked list via recursion result in null. This is my code so far:
public static int i = 0;
public static Link.Node findnthToLastRecursion(Link.Node node, int pos) {
if(node == null) return null;
else{
findnthToLastRecursion(node.next(), pos);
if(++i == pos) return node;
return null;
}
Can anyone help me understand where I'm going wrong here?
This is my iterative solution which works fine, but I'd really like to know how to translate this into recursion:
public static Link.Node findnthToLast(Link.Node head, int n) {
if (n < 1 || head == null) {
return null;
}
Link.Node pntr1 = head, pntr2 = head;
for (int i = 0; i < n - 1; i++) {
if (pntr2 == null) {
return null;
} else {
pntr2 = pntr2.next();
}
}
while (pntr2.next() != null) {
pntr1 = pntr1.next();
pntr2 = pntr2.next();
}
return pntr1;
}
You need to go to the end and then count your way back, make sure to pass back the node each time its passed back. I like one return point
public static int i = 0;
public static Link.Node findnthToLastRecursion(Link.Node node, int pos) {
Link.Node result = node;
if(node != null) {
result = findnthToLastRecursion(node.next, pos);
if(i++ == pos){
result = node;
}
}
return result;
}
Working example outputs 7 as 2 away from the 9th and last node:
public class NodeTest {
private static class Node<E> {
E item;
Node<E> next;
Node<E> prev;
Node(Node<E> prev, E element, Node<E> next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}
/**
* #param args
*/
public static void main(String[] args) {
Node first = null;
Node prev = null;
for (int i = 0; i < 10; i++) {
Node current = new Node(prev, Integer.toString(i),null);
if(i==0){
first = current;
}
if(prev != null){
prev.next = current;
}
prev = current;
}
System.out.println( findnthToLastRecursion(first,2).item);
}
public static int i = 0;
public static Node findnthToLastRecursion(Node node, int pos) {
Node result = node;
if (node != null) {
result = findnthToLastRecursion(node.next, pos);
if (i++ == pos) {
result = node;
}
}
return result;
}
}
No need for static variables.
public class List {
private Node head = null;
// [...] Other methods
public Node findNthLastRecursive(int nth) {
if (nth <= 0) return null;
return this.findNthLastRecursive(this.head, nth, new int[] {0});
}
private Node findNthLastRecursive(Node p, int nth, int[] pos) {
if (p == null) {
return null;
}
Node n = findNthLastRecursive(p.next, nth, pos);
pos[0]++;
if (pos[0] == nth) {
n = p;
}
return n;
}
}
You can do this a couple of ways:
recurse through the list once to find the list length, then write a recursive method to return the kth element (a much easier problem).
use an auxiliary structure to hold the result plus the remaining length; this essentially replaces the two recursions of the first option with a single recursion:
static class State {
Link.Node result;
int trailingLength;
}
public static Link.Node findnthToLastRecursion(Link.Node node, int pos) {
if(node == null) return null;
State state = new State();
findnthToLastRecursion(node, pos, state);
return state.result;
}
private static void findnthToLastRecursion(Link.Node node, int pos, State state) {
if (node == null) {
state.trailingLength = 0;
} else {
findnthToLastRecursion(node.next(), state);
if (pos == state.trailingLength) {
state.result = node;
}
++state.trailingLength;
}
}
I misunderstood the question. Here is an answer based on your iterative solution:
public static Link.Node findnthToLast(Link.Node head, int n) {
return findnthToLastHelper(head, head, n);
}
private static Link.Node findnthToLastHelper(Link.Node head, Link.Node end, int n) {
if ( end == null ) {
return ( n > 0 ? null : head);
} elseif ( n > 0 ) {
return findnthToLastHelper(head, end.next(), n-1);
} else {
return findnthToLastHelper(head.next(), end.next(), 0);
}
}
actually you don't need to have public static int i = 0; . for utill method the pos is :
pos = linked list length - pos from last + 1
public static Node findnthToLastRecursion(Node node, int pos) {
if(node ==null){ //if null then return null
return null;
}
int length = length(node);//find the length of the liked list
if(length < pos){
return null;
}
else{
return utill(node, length - pos + 1);
}
}
private static int length(Node n){//method which finds the length of the linked list
if(n==null){
return 0;
}
int count = 0;
while(n!=null){
count++;
n=n.next;
}
return count;
}
private static Node utill(Node node, int pos) {
if(node == null) {
return null;
}
if(pos ==1){
return node;
}
else{
return utill(node.next, pos-1);
}
}
Here node.next is the next node. I am directly accessing the next node rather than calling the next() method. Hope it helps.
This cheats (slightly) but it looks good.
public class Test {
List<String> list = new ArrayList<> (Arrays.asList("Zero","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten"));
public static String findNthToLastUsingRecursionCheatingALittle(List<String> list, int n) {
int s = list.size();
return s > n
// Go deeper!
? findNthToLastUsingRecursionCheatingALittle(list.subList(1, list.size()), n)
// Found it.
: s == n ? list.get(0)
// Too far.
: null;
}
public void test() {
System.out.println(findNthToLastUsingRecursionCheating(list,3));
}
public static void main(String args[]) {
new Test().test();
}
}
It prints:
Eight
which I suppose is correct.
I have use List instead of some LinkedList variant because I do not want to reinvent anything.
int nthNode(struct Node* head, int n)
{
if (head == NULL)
return 0;
else {
int i;
i = nthNode(head->left, n) + 1;
printf("=%d,%d,%d\n", head->data,i,n);
if (i == n)
printf("%d\n", head->data);
}
}
public class NthElementFromLast {
public static void main(String[] args) {
List<String> list = new LinkedList<>();
Stream.of("A","B","C","D","E").forEach(s -> list.add(s));
System.out.println(list);
System.out.println(getNthElementFromLast(list,2));
}
private static String getNthElementFromLast(List list, int positionFromLast) {
String current = (String) list.get(0);
int index = positionFromLast;
ListIterator<String> listIterator = list.listIterator();
while(positionFromLast>0 && listIterator.hasNext()){
positionFromLast--;
current = listIterator.next();
}
if(positionFromLast != 0) {
return null;
}
String nthFromLast = null;
ListIterator<String> stringListIterator = list.listIterator();
while(listIterator.hasNext()) {
current = listIterator.next();
nthFromLast = stringListIterator.next();
}
return nthFromLast;
}
}
This will find Nth element from last.
My approach is simple and straight,you can change the array size depending upon your requirement:
int pos_from_tail(node *k,int n)
{ static int count=0,a[100];
if(!k) return -1;
else
pos_from_tail(k->next,n);
a[count++]=k->data;
return a[n];
}
You'll have make slight changes in the code:
public static int i = 0;
public static Link.Node findnthToLastRecursion(Link.Node node, int pos) {
if(node == null) return null;
else{
**Link.Node temp = findnthToLastRecursion(node.next(), pos);
if(temp!=null)
return temp;**
if(++i == pos) return node;
return null;
}
}

Categories