Home Ask Login Register

Developers Planet

Your answer is one click away!

roony February 2016

how to turn a linked list data into a number?

I have a question with a linked list. Each object has two variables: a pointer to the next object, and its own value. The point of the question is to check whether the number is palindrome. I'm trying to convert the numbers ( in the order they were given) into a N variable in order to do the reverse check but I've failed so far, either overflowing with the long\int variables or having the decimal point(.) and Exx input after the first digit, if using double.

This is my current code:

public class driver

{    // Driver program

        public static void main(String args[])
        {
        int count=12;
        double number=0;
        double x=1;
        while(count>0)
        {
            number=number+x*(Math.pow(10,count));
            System.out.println(number);
            count--;
            if(x<10)
                x++;
            else x=1;
        }
        System.out.println(num);
    }

I assume there's an easier way to build the number except the POW?

Your help( and any future ideas regarding the palindrome problem and linked lists) would be appreciate.

Answers


Gavriel February 2016

Copy the elements to a stack, then compare the elements in the list with the elements in the stack. Pseudocode:

node = list.head;
while (node != null) {
    stack.push(node.value);
    node = node.next;
}
node = list.head;
boolean palindrome = true;
while (node != null) {
    if (stack.pop != node.value) {
        palindrome = false;
        break;
    }
}
if (palindrome) {
    print "palindrome"
} else {
    print "not a palindrome"
}

Post Status

Asked in February 2016
Viewed 1,720 times
Voted 14
Answered 1 times

Search




Leave an answer


Quote of the day: live life