Question

My project is to see if a user inputted string is a palindrome or not. Firstly, the string is to be put into a Linked list and then copied into a second linked list where I reverse the list completely in order to compare them.

the linked list is my own class as well all the methods within it. I have confirmed that the linked list works as does the reverse method.

Where i run into problems is when i try and compare the 2 from the beginning of the lists. This is what i've tried:

package palindromes;
import data_structures.*;
import java.util.Iterator;

public class Palindrome
{
    public boolean isPalindrome(String s)
    {
        if (s.length() <= 1) // base case
            return true;
        String originalList = s.replaceAll("[\\W]", "").toLowerCase();

        LinkedList<Character> list1 = new LinkedList<Character>();
        LinkedList<Character> rlist = new LinkedList<Character>();
        for (int i = 0; i < originalList.length(); i++)
        {
            list1.addLast(originalList.charAt(i));
        }
        rlist = list1;
        rlist.reverse();
        Iterator<Character> l1 = list1.iterator();
        Iterator<Character> l2 = rlist.iterator();
        while (l1.hasNext() && l2.hasNext())
        {
            if (l1.next() != l1.next())
                return false;
        }
        return true;
    }
}

I try to iterate through both lists in the while loop but when i go to test the data of the nodes it is incorrect.

Please let me know if you need added information or clarification.

My question is how do i fix my code so that i am able to compare the lists sequentially to see if the inputted string is a palindrome or not?

Était-ce utile?

La solution

This can be achieved in following way:

     List<String> list = new ArrayList<String>();

     list.add("a");
     list.add("b");
     list.add("c");
     list.add("c");
     list.add("b");
     list.add("a");
     int size = list.size();
     for(int i = 0; i<size/2; i++)
     {
         if(list.get(i) == list.get(size - 1))
            System.out.println("list is palindrome");

     }

Autres conseils

rlist = list1;

is the problem. Both rlist and list1 are just two references to the same List.

replace it with

rlist = new LinkedList<Character>(list1);

this will create new List and copy all the elements in the list1 to that new list. rlist is referring to the new list while list1 refers to the old list.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top