Add Palindrome Linked List (Fixes #2360) (#2746)

This commit is contained in:
Aitor Fidalgo Sánchez 2021-10-30 07:21:08 +02:00 committed by GitHub
parent 332f63b942
commit 5834a949a6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -0,0 +1,47 @@
package Misc;
import java.util.Stack;
import DataStructures.Lists.SinglyLinkedList;
/**
* A simple way of knowing if a singly linked list is palindrome is to
* push all the values into a Stack and then compare the list to popped
* vales from the Stack.
*
* See more: https://www.geeksforgeeks.org/function-to-check-if-a-singly-linked-list-is-palindrome/
*/
public class PalindromeSinglyLinkedList {
public static void main(String[] args) {
SinglyLinkedList linkedList = new SinglyLinkedList();
linkedList.insertHead(3);
linkedList.insertNth(2, 1);
linkedList.insertNth(1, 2);
linkedList.insertNth(2, 3);
linkedList.insertNth(3, 4);
if (isPalindrome(linkedList)) {
System.out.println("It's a palindrome list");
} else {
System.out.println("It's NOT a palindrome list");
}
}
public static boolean isPalindrome(SinglyLinkedList linkedList) {
boolean ret = true;
Stack<Integer> linkedListValues = new Stack<>();
for (int i = 0; i < linkedList.size(); i++) {
linkedListValues.push(linkedList.getNth(i));
}
for (int i = 0; i < linkedList.size(); i++) {
if (linkedList.getNth(i) != linkedListValues.pop()) {
ret = false;
break;
}
}
return ret;
}
}