Why do we want to use a helper method in Java? - java

I came across this block of code when I was studying for java CS61b, which used a helper method. As to why we use helper method, the explanation I got is that it makes it easier to do the recursive task. But I have trouble visualizing the alternative options where we don't use a helper method because I have difficulting write the solution. Does that mean using a helper method is the only way? I wish I could compare the two solutions and better understand the usage of a helper method.
here's the code in question:
//Same as get, but uses recursion.
public int getRecursive(int index) {
if (index>size-1) {
return 0;
}
node p = sentinel;
return getRecursiveHelper(p, index);
}
public int getRecursiveHelper(node p, int i) {
if (i==0) {
return p.next.item;
} else {
p = p.next;
i -= 1;
}
return getRecursiveHelper(p, i);
}
the below is the full code:
public class LinkedListDeque {
public node sentinel;
public int size;
public class node {
public node prev;
public int item;
public node next;
public node(node p, int i, node n) {
prev = p;
item = i;
next = n;
}
}
// Creates an empty list
public LinkedListDeque() {
sentinel = new node(null, 63, null);
sentinel.prev = sentinel;
sentinel.next = sentinel;
size = 0;
}
// Adds an item of type T to the front of the deque.
public void addFirst(int x) {
sentinel.next = new node(sentinel, x, sentinel.next);
sentinel.next.next.prev = sentinel.next;
size += 1;
}
// Adds an item of type T to the back of the deque.
public void addLast(int x) {
sentinel.prev = new node(sentinel.prev, x, sentinel);
sentinel.prev.prev.next = sentinel.prev;
size += 1;
}
// Returns true if deque is empty, false otherwise.
public boolean isEmpty() {
if (size == 0) {
return true;
}
return false;
}
// Returns the number of items in the deque.
public int size() {
return size;
}
// Prints the items in the deque from first to last, separated by a space. Once all the items have been printed, print out a new line.
public void printDeque() {
node p = sentinel.next;
for (int i=0; i<size; i++) {
System.out.print(p.item + " ");
p = p.next;
}
System.out.println();
}
// Removes and returns the item at the front of the deque. If no such item exists, returns null.
public int removeFirst() {
if (size==0) {
return 0;
}
int x = sentinel.next.item;
sentinel.next = sentinel.next.next;
sentinel.next.prev = sentinel;
size -= 1;
return x;
}
// Removes and returns the item at the back of the deque. If no such item exists, returns null.
public int removeLast() {
if (size==0) {
return 0;
}
int x = sentinel.prev.item;
sentinel.prev = sentinel.prev.prev;
sentinel.prev.next = sentinel;
size -= 1;
return x;
}
// Gets the item at the given index, where 0 is the front, 1 is the next item, and so forth. If no such item e
public int get(int index) {
if (index>size-1) {
return 0;
}
node p = sentinel.next;
for (int i=0; i<index; i++) {
p = p.next;
}
return p.item;
}
//Same as get, but uses recursion.
public int getRecursive(int index) {
if (index>size-1) {
return 0;
}
node p = sentinel;
return getRecursiveHelper(p, index);
}
public int getRecursiveHelper(node p, int i) {
if (i==0) {
return p.next.item;
} else {
p = p.next;
i -= 1;
}
return getRecursiveHelper(p, i);
}
public static void main(String[] args) {
LinkedListDeque L = new LinkedListDeque();
L.addFirst(2);
L.addFirst(1);
L.addFirst(0);
L.addLast(3);
L.addLast(4);
L.addLast(5);
System.out.println(L.get(7));
}
}

Related

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.

Linked List bubble sort method not sorting elements

I am trying to sort a linked list with a bubble sort method, but when I try to sort the elements they remain unsorted. When I call my linked method it builds a linked list with parameters n and m which indicate length of the linked list and it represents a set of random integers m-1
Node class
public class iNode{
public int item;
public iNode next;
public iNode(int i, iNode n){
item = i;
next = n;
}
public iNode(int i){
item = i;
next = null;
}
// Node class
public int getItem() {
return this.item;
}
Node List class
public class iNode_List {
public static iNode head;
public static int size;
public iNode_List(){
this.head = null;
this.size = 0;
}
public static iNode linked(int n, int m){ // builds linked list
iNode previous;
iNode current;
int i = 0;
previous = null;
while (i < n) {
current = new iNode(ThreadLocalRandom.current().nextInt(0, m-1), previous);
previous = current;
head = current;
i++;
}
return previous;
}
public static void print() { // prints linked list
iNode currentNode = head;
while(currentNode != null) {
int data = currentNode.getItem();
System.out.println(data);
currentNode = currentNode.next;
}
}
public static void Bubble_Sort (){ // bubble sort method
if (size > 1) {
for (int i = 0; i < size; i++ ) {
iNode currentNode = head;
iNode next = head.next;
for (int j = 0; j < size - 1; j++) {
if (currentNode.item > next.item) {
int temp = currentNode.item;
currentNode.item = next.item;
next.item = temp;
}
currentNode = next;
next = next.next;
}
}
}
}
List class
public class list {
public static void main (String [] args) throws IOException{
iNode_List x = new iNode_List();
int choice;
x.linked(10, 9);
x.print();
System.out.println();
System.out.println("Which method would you like to implement? "); // method --------
Scanner scan = new Scanner (System.in);
choice = scan.nextInt();
switch (choice) {
case 1 : Compare_Loop(x) ;
break ;
case 2 : Bubble_Sort( x) ;
break ;
case 3 : Merge_Sort( x);
break ;
case 4 : Boolean( x);
break ;
}
}
public static void Compare_Loop (iNode_List x){
System.out.println();
x.Compare_Loop();
x.print();
}
public static void Bubble_Sort(iNode_List x){
System.out.println();
x.Bubble_Sort();
x.print();
}
public static void Merge_Sort(iNode_List x){
System.out.println();
x.Merge_Sort(null);
x.print();
}
public static void Boolean (iNode_List x){
System.out.println();
//x.Boolean();
x.print();
}

Sorting sets of 4 ints in circular list

I am playing around with circular linked list to represent polynomials with it.
Here is what I have so far:
Class for parts of polynomial:
public class Wielomian {
int wsp;
int a;
int b;
int c;
public Wielomian(){
wsp=0;
a=-1;
b=-1;
c=-1;
}
public Wielomian(int wsp, int a, int b, int c){
this.wsp = wsp;
this.a = a;
this.b = b;
this.c = c;
}
public String toString(){
return wsp+"(x^"+a+")(y^"+b+")(z^"+c+")";
}
}
wsp is coefficient and a,b,c are exponents of x, y and z.
Node:
public class Node {
protected Object data;
protected Node link;
public Node() {
link = null;
data = 0;
}
public Node(Object d,Node n) {
data = d;
link = n;
}
public void setLink(Node n) {
link = n;
}
public void setData(Object d) {
data = d;
}
public Node getLink() {
return link;
}
public Object getData() {
return data;
}
}
List:
class linkedList {
protected Node start ;
protected Node end ;
public int size ;
public linkedList() {
start = null;
end = null;
size = 0;
}
public boolean isEmpty() {
return start == null;
}
public int getSize() {
return size;
}
public void insertAtStart(Object val) {
Node nptr = new Node(val,null);
nptr.setLink(start);
if(start == null) {
start = nptr;
nptr.setLink(start);
end = start;
}
else {
end.setLink(nptr);
start = nptr;
}
size++ ;
}
/* Function to insert element at end */
public void insertAtEnd(Object val) {
Node nptr = new Node(val,null);
nptr.setLink(start);
if(start == null) {
start = nptr;
nptr.setLink(start);
end = start;
}
else {
end.setLink(nptr);
end = nptr;
}
size++ ;
}
/* Function to insert element at position */
public void insertAtPos(Object val , int pos) {
Node nptr = new Node(val,null);
Node ptr = start;
pos = pos - 1 ;
for (int i = 1; i < size - 1; i++)
{
if (i == pos)
{
Node tmp = ptr.getLink() ;
ptr.setLink( nptr );
nptr.setLink(tmp);
break;
}
ptr = ptr.getLink();
}
size++ ;
}
/* Function to delete element at position */
public void deleteAtPos(int pos) {
if (size == 1 && pos == 1) {
start = null;
end = null;
size = 0;
return ;
}
if (pos == 1) {
start = start.getLink();
end.setLink(start);
size--;
return ;
}
if (pos == size) {
Node s = start;
Node t = start;
while (s != end) {
t = s;
s = s.getLink();
}
end = t;
end.setLink(start);
size --;
return;
}
Node ptr = start;
pos = pos - 1 ;
for (int i = 1; i < size - 1; i++) {
if (i == pos) {
Node tmp = ptr.getLink();
tmp = tmp.getLink();
ptr.setLink(tmp);
break;
}
ptr = ptr.getLink();
}
size-- ;
}
}
And I realised I need another add method that will and sort those parts of polynomial while adding - first by exponent of x, if 2 will have equal then by exponent of y and so on.
The elements of list will be parts of polynomial and there also will be "head" which will be linked to the part with highest exponent at "x" and the last part of polynomial will be linked to this "head" making whole list circular. Head will have coefficient that equals 0 and exponats that equal -1 each. But I have no idea how to implement such method without ruining all the links etc. etc. I hope You guys can help me :)
I would also like to know best way to display my polynomial later. Will it be some kind of iteration through parts of polynomial and adding them to String until i reach "head"?

I have ONE pre-compile error

Here is the assignment:
Modify the maze problem in Chapter 4 so that it can start from a user defined starting position (other than 0, 0) and search for a user defined ending point.
The whole program seems to look fine, and I still have to mess with the user-inputted part, but there is one line that has an error and I don't know how to get rid of it. Any help would be appreciated.
The line that has the error is:
StackADT stack = new LinkedStackADT ();
And it is telling me that LinkedStackADT cannot be resolved to a type.
Also, how do I get the maze to take in user-defined starting positions and ending points? Thanks for any possible help!
public class Maze
{
public interface StackADT<T> {
public void push (T element);
public T pop();
public T peek();
public boolean isEmpty();
public int size();
public String toString();
}
public static void main(String[] args){
abstract class LinkedStack<T> implements StackADT<T>
{
private int count;
private LinearNode<T> top;
public LinkedStack()
{
count = 0;
top = null;
}
class LinearNode<T>
{
private LinearNode<T> next;
private T element;
public LinearNode()
{
next = null;
element = null;
}
public LinearNode(T elem)
{
next = null;
element = elem;
}
public LinearNode<T> getNext()
{
return next;
}
public void setNext(LinearNode<T> node)
{
next = node;
}
public T getElement()
{
return element;
}
public void setElement(T elem)
{
element = elem;
}
}
class Position
{
private int x;
private int y;
Position ()
{
x = 0;
y = 0;
}
public int getx()
{
return x;
}
public int gety()
{
return y;
}
public void setx1(int a)
{
x = a;
}
public void sety(int a)
{
y = a;
}
public void setx(int x2) {
}
}
private final int TRIED = 3;
private final int PATH = 7;
private int [][] grid = {{1,1,1,0,1,1,0,0,0,1,1,1,1},
{1,0,0,1,1,0,1,1,1,1,0,0,1},
{1,1,1,1,1,0,1,0,1,0,1,0,0},
{0,0,0,0,1,1,1,0,1,0,1,1,1},
{1,1,1,0,1,1,1,0,1,0,1,1,1},
{1,0,1,0,0,0,0,1,1,1,0,0,1},
{1,0,1,1,1,1,1,1,0,1,1,1,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0},
{1,1,1,1,1,1,1,1,1,1,1,1,1}};
public StackADT<Position> push_new_pos(int x, int y,
StackADT<Position> stack)
{
Position npos = new Position();
npos.setx1(x);
npos.sety(y);
if (valid(npos.getx(),npos.gety()))
stack.push(npos);
return stack;
}
public boolean traverse ()
{
boolean done = false;
Position pos = new Position();
Object dispose;
StackADT<Position> stack = new LinkedStackADT<Position> ();
stack.push(pos);
while (!(done))
{
pos = stack.pop();
grid[pos.getx()][pos.gety()] = TRIED; // this cell has been tried
if (pos.getx() == grid.length-1 && pos.gety() == grid[0].length-1)
done = true; // the maze is solved
else
{
stack = push_new_pos(pos.getx(),pos.gety() - 1, stack);
stack = push_new_pos(pos.getx(),pos.gety() + 1, stack);
stack = push_new_pos(pos.getx() - 1,pos.gety(), stack);
stack = push_new_pos(pos.getx() + 1,pos.gety(), stack);
}
}
return done;
}
private boolean valid (int row, int column)
{
boolean result = false;
if (row >= 0 && row < grid.length &&
column >= 0 && column < grid[row].length)
if (grid[row][column] == 1)
result = true;
return result;
}
public String toString ()
{
String result = "\n";
for (int row=0; row < grid.length; row++)
{
for (int column=0; column < grid[row].length; column++)
result += grid[row][column] + "";
result += "\n";
}
return result;
}
}
}
}
You don't have a type (or a class) defined as LinkedStackADT. You do have a type LinkedStack, but it's abstract so the new will fail. If you remove the abstract keyword from LinkedStack, it should be instantiatable. (note: instantiatable is not a real word)

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