How to traverse linked list in c++?

Use recursion to traverse linked list? Java?

  • Given the following class and inner class: public class LinkedList<T extends Comparable<T>> { public class Node { private T data; private Node next; public Node(T data) { this.data = data; next = null; } } Node head; }

  • Answer:

    I am not giving straight answer. Also the following code is functioning but not upto standards. You can modify class Node { private int data; private Node next; public Node(int data, Node Next) { this.data = data; next = Next; } public int getData(){ return data; } public Node getNext(){ return next;} public void setNext(Node A){next=A;} } public class list { Node head; public list() { head=null; } public void insert(int x) { head=new Node(x,head); } public void rev(Node A) { if(A!=null) System.out.println(A.getData()); if(A !=null) rev(A.getNext()); else return; } public Node getHead(){return head;} public static void main(String []a) { list A=new list(); A.insert(20); A.insert(10); A.insert(5); A.insert(17); A.insert(67); A.rev(A.getHead()); } }

James Bond at Yahoo! Answers Visit the source

Was this solution helpful to you?

Other answers

Are you able to report back that using recursion to traverse a linked list is a particularly stupid idea? Yah, you can do it, but if your linked list is huge (and sometimes they are) you're gonna blow the stack. Literally. Recursion has its place, and iteration has its place, and if you mix them up you're asking for heartburn.

Unca Alby

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.