Question

In: Computer Science

IN JAVA: Implement an algorithm to check whether a LinkedList is a palindrome. 2 methods should...

IN JAVA:

Implement an algorithm to check whether a LinkedList is a palindrome.

2 methods should be implemented:

  1. Constant space, i.e. without creating extra copies of the linked list
  2. Unrestricted space

q1:

/ For this implementation you should use constant space

  // Note: you are free to add any extra methods,

  // but this method has to be used

  public static boolean isPalindromeRestricted(ListNode head) {

    // Your code goes here

    return false;

  }

q2:

// For this implementation the space is not restricted

  // Note: you are free to add any extra methods,

  // but this method has to be used

  public static boolean isPalindromeUnrestricted(ListNode head) {

    // Your code goes here

    return false;

  }

Solutions

Expert Solution

A number is a palindrome if it reads the same forwards as it does backward. For example, the number 1233321 is a palindrome. Linked lists can also be palindromes if they have the same order of elements when traversed forwards and backward​.

Pseudocode to check whether the linked list is palindrome or not :

boolean isListPalindrome(ListNode head)
{
// if the linked list is empty or having only one node
if(head == NULL or head.next == NULL)
return True
stack <List Datatype> S
ListNode temp = head
// traversing the linked list and pushing the elements into stack
while(temp is not NULL)
{
S.push(temp.data)
temp=temp.next
}
temp = head
// again traversing the linked list to compare
while(temp is not NULL)
{
topOfStack = S.top()
S.pop()
if(topOfStack is not equal temp)
return False
temp=temp.next
}
return True
}

Algorithm :

  • First, traverse the whole linked list, storing the value of each element in a stack at each step.
  • Traverse the whole linked list again, this time popping out elements from the stack and comparing them with the elements in the linked list. If all the elements are the same, then the linked list is a palindrome.
  • Traverse the given list from head to tail and push every visited node to stack.
  • Traverse the list again. For every visited node, pop a node from stack and compare data of popped node with currently visited node.
  • If all nodes matched, then return true, else false.

Java Program implementing isPalindromeRestricted() :


import java.util.*;

class LinkedList_Restricted
{
public static void main(String args[])
{
Node one = new Node('M');
Node two = new Node('A');
Node three = new Node('D');
Node four = new Node('A');
Node five = new Node('M');
one.ptr = two;
two.ptr = three;
three.ptr = four;
four.ptr = five;
boolean condition = isPalindromeRestricted(one);
System.out.println("isPalidrome :" + condition);
}
static boolean isPalindromeRestricted(Node head)
{
Node temp = head;
boolean ispalin = true;
Stack<Integer> stack = new Stack<Integer>();
while (temp != null)
{
stack.push(temp.data);
temp = temp.ptr;
}
while (head != null)
{
int i = stack.pop();
if (head.data == i)
{
ispalin = true;
}
else
{
ispalin = false;
break;
}
head = head.ptr;
}
return ispalin;
}
}
class Node
{
int data;
Node ptr;
Node(int d)
{
ptr = null;
data = d;
}
}

OUTPUT

Java Program implementing isPalindromeUnrestricted() :

class Linked_List_Unrestricted
{
Node head;
Node ptr, fast_ptr, second_half;

/* Linked list Node*/
class Node
{
char data;
Node next;
Node(char d)
{
data = d;
next = null;
}
}
/* Function to check if given linked list is palindrome or not */
boolean isPalindrome(Node head)
{
ptr = head;
fast_ptr = head;
Node prev_of_slow_ptr = head;
Node midnode = null;                        // To handle odd size list
boolean res = true;                           // Initialize result
if (head != null && head.next != null)
{
/* Get the middle of the list. Move ptr by 1 and fast_ptr by 2, tr will have the middle node */
while (fast_ptr != null && fast_ptr.next != null)
{
fast_ptr = fast_ptr.next.next;
prev_of_slow_ptr = ptr;
ptr = ptr.next;
}
/* fast_ptr would become NULL when there are even elements in the list and not NULL for odd elements. */
if (fast_ptr != null)
{
midnode = ptr;
ptr = ptr.next;
}
//Reverse the second half and compare it with first half
second_half = ptr;
prev_of_slow_ptr.next = null;        // NULL terminate first half
reverse();                                                // Reverse the second half
res = compareLists(head, second_half);
                                                   // Construct the original list back
reverse();                                // Reverse the second half again
if (midnode != null)
{
// If there was a mid node (odd size case) which was not part of either first half or second half.
prev_of_slow_ptr.next = midnode;
midnode.next = second_half;
}
else
prev_of_slow_ptr.next = second_half;
}
return res;
}

/* Function to reverse the linked list */
void reverse()
{
Node prev = null;
Node current = second_half;
Node next;
while (current != null)
{
next = current.next;
current.next = prev;
prev = current;
current = next;
}
second_half = prev;
}
/* Function to check if two input lists have same data*/
boolean compareLists(Node head1, Node head2)
{
Node temp1 = head1;
Node temp2 = head2;
while (temp1 != null && temp2 != null)
{
if (temp1.data == temp2.data)
{
temp1 = temp1.next;
temp2 = temp2.next;
}
else
return false;
}
if (temp1 == null && temp2 == null)
return true;
       return false;
}

/* Push a node to linked list*/
public void push(char new_data)
{
Node new_node = new Node(new_data);
       new_node.next = head;
/* Move the head to point to new Node */
head = new_node;
}
// Print a given linked list
void printList(Node ptr)
{
while (ptr != null)
{
System.out.print(ptr.data + "->");
ptr = ptr.next;
}
System.out.println("NULL");
}
   public static void main(String[] args)
{
   Linked_List_Unrestricted LLU = new Linked_List_Unrestricted();
   char str[] = { 'M', 'A', 'L', 'A', 'Y', 'A', 'L','A','M' };
String string = new String(str);
for (int i = 0; i < 9; i++)
{
LLU.push(str[i]);
LLU.printList(LLU.head);

}
if (LLU.isPalindrome(LLU.head) != false)
       {
       System.out.println("Is Palindrome");
       System.out.println("");
       }
       else
       {
       System.out.println("Not Palindrome");
       System.out.println("");
}
}
}
OUTPUT


Related Solutions

Please write a Java algorithm solving the following problem: Implement a Java method to check if...
Please write a Java algorithm solving the following problem: Implement a Java method to check if a binary tree is balanced. For this assignment, a balanced tree is defined to be a tree such that the heights of the two subtrees of any node never differ by more than one. 1. First, please create the following two classes supporting the Binary Tree Node and the Binary Tree: public class BinTreeNode<T> { private T key; private Object satelliteData; private BinTreeNode<T> parent;...
Java Palindrome Use StringBuilder concept to create a palindrome checker.   Method should be called pCheck. Must...
Java Palindrome Use StringBuilder concept to create a palindrome checker.   Method should be called pCheck. Must use var-arg concept.   Class name for this program is Palindrome.   Must pass this test:: public class PalindromeTest { public static void main(String[] args) { Palindrome palindrome = new Palindrome(); boolean answer = palindrome.pCheck("racecar", "Bell", "elle", "bunny"); System.out.println(“These are palindromes: " + answer); } }
Write an algorithm to check equality of two link lists.(java)
Write an algorithm to check equality of two link lists.(java)
Using Java implement a searching algorithm to solve the following problem (please specify the searching algorithm...
Using Java implement a searching algorithm to solve the following problem (please specify the searching algorithm being used) Requirements Choose one problem with an algorithm and implement it. You should show and explain the result whatever you got. I recommend using N-Queen problem (at least N=8 or more) or any simple perfect games. For example, - N-Queen problem with hill climbing - N-Queen problem with simulated annealing - N-Queen problem with genetic algorithm - Tic-Tac-Toe with Minimax
Code in Java Given the LinkedList class that is shown below Add the following methods: add(String...
Code in Java Given the LinkedList class that is shown below Add the following methods: add(String new_word): Adds a linkedlist item at the end of the linkedlist print(): Prints all the words inside of the linkedlist length(): Returns an int with the length of items in the linkedlist remove(int index): removes item at specified index itemAt(int index): returns LinkedList item at the index in the linkedlist public class MyLinkedList { private String name; private MyLinkedList next; public MyLinkedList(String n) {...
Problem Description:A very simple algorithm (Luhn Algorithm) to check whether a credit card number is valid...
Problem Description:A very simple algorithm (Luhn Algorithm) to check whether a credit card number is valid is shown below:We assume that there are 16 digits in a credit card number.Start from the first digit of the credit card number as in position 1; second digit as in position 2; so on until the last digit as in position 16;If a digit is in even numbered position, take the digit itself as its representative;If a digit is in odd numbered position,...
Define empty methods in Queue class using LinkedList class in Java ------------------------------------------------------------------------------- //Queue class public class...
Define empty methods in Queue class using LinkedList class in Java ------------------------------------------------------------------------------- //Queue class public class Queue{ public Queue(){ // use the linked list } public void enqueue(int item){ // add item to end of queue } public int dequeue(){ // remove & return item from the front of the queue } public int peek(){ // return item from front of queue without removing it } public boolean isEmpty(){ // return true if the Queue is empty, otherwise false }...
Define empty methods in Stack class using LinkedList class in Java ------------------------------------------------------------------------------- //Stack class public class...
Define empty methods in Stack class using LinkedList class in Java ------------------------------------------------------------------------------- //Stack class public class Stack{ public Stack(){ // use LinkedList class } public void push(int item){ // push item to stack } public int pop(){ // remove & return top item in Stack } public int peek(){ // return top item in Stack without removing it } public boolean isEmpty(){ // return true if the Stack is empty, otherwise false } public int getElementCount(){ // return current number...
Tasks 2 Write algorithms in pseudocode to implement a LinkedList The following operations must be performed...
Tasks 2 Write algorithms in pseudocode to implement a LinkedList The following operations must be performed on the LinkedList: *Add an element *Insert an element at a given position x. *Retrieve/Read the value of an element at position y. *Delete an element from position z. (x,y and z represent any value in the valid range of indices of the LinkedList).
Java Programm please! Design and implement an algorithm using recursion and backtracking to sort an array...
Java Programm please! Design and implement an algorithm using recursion and backtracking to sort an array of integers into ascending order. Consider the given array as input and produce a sorted array as output. Each time you take an integer from the input array, place it at the end of the output array. If the result is unsorted, backtrack.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT