IT_Philic
IT_Philic

Reputation: 321

How Can I add linked list to vector?

I have to return elements of a linked list in a vector form.How can I return linkedlist in vector form.I have tried following but unable to get the right result.Can anyone tell me what I did wrong?

    package BasicList1;


    import java.util.Vector;

    public class BasicList1 implements ListInterface{

        static String[] testcase1 = {"3","1","2","6","7","4","5"};

        public static void main (String[] args){
            BasicList1 testInstance = new BasicList1();
            ListNode head = new ListNode(testcase1[0]);
            ListNode node = head;
            System.out.println(testInstance.elements(head));
            System.out.println(testInstance.length(head));
        }

        public BasicList1 getBasicList(String data){
            return this;
        }

        //write your code here
        public Vector<String> elements(ListNode head){
                ListNode temp=head;
        Vector v=new Vector();
        while(temp!=null){
            System.out.println(temp.data);
            temp=temp.next;
            v.addElement(temp);
        }
        return v;
        }

        public int length(ListNode head) {
            int count=0;
            for(int i=0;i<testcase1.length;i++){
                count++;
            }
            return count;
        }

Upvotes: 0

Views: 275

Answers (1)

Ambrish
Ambrish

Reputation: 3677

The output that you are getting is like:

3
1
2
6
7
4
5
7 <= Length of the list

But the length of vector is 7 and sequence of element is => 1, 2, 6, 7, 4, 5, null.

This is because you are moving to next element before adding it to Vector. Code:

        System.out.println(temp.data);
        temp=temp.next;
        v.addElement(temp);

Correct way should be:

        System.out.println(temp.data);
        v.addElement(temp);
        temp=temp.next;

Upvotes: 1

Related Questions