From 5834a949a634d1b116b21d4d8e095e643a09dcf1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aitor=20Fidalgo=20S=C3=A1nchez?= <64830228+aitorfi@users.noreply.github.com> Date: Sat, 30 Oct 2021 07:21:08 +0200 Subject: [PATCH] Add Palindrome Linked List (Fixes #2360) (#2746) --- Misc/PalindromeSinglyLinkedList.java | 47 ++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Misc/PalindromeSinglyLinkedList.java diff --git a/Misc/PalindromeSinglyLinkedList.java b/Misc/PalindromeSinglyLinkedList.java new file mode 100644 index 00000000..06a0de41 --- /dev/null +++ b/Misc/PalindromeSinglyLinkedList.java @@ -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 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; + } +}