Java – recursively find the nth element in the linked list
•
Java
I'm practicing basic data structures. I have some difficulties in recursion I understand how to do this iteratively, but I recursively return all attempts to return the nth node from the last linked list to 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 what went wrong?
This is my iterative solution and works well, but I really want to know how to turn it 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; }
Solution
You need to end and then calculate your way to ensure that each return node is returned I like a regression 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; }
The working example outputs 7 as 2 from the 9th and last nodes:
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; } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码