mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-07 17:56:02 +08:00
Cleanup PalindromeSinglyLinkedList
(#4336)
This commit is contained in:
@ -11,39 +11,23 @@ import java.util.Stack;
|
|||||||
* See more:
|
* See more:
|
||||||
* https://www.geeksforgeeks.org/function-to-check-if-a-singly-linked-list-is-palindrome/
|
* https://www.geeksforgeeks.org/function-to-check-if-a-singly-linked-list-is-palindrome/
|
||||||
*/
|
*/
|
||||||
public class PalindromeSinglyLinkedList {
|
public final class PalindromeSinglyLinkedList {
|
||||||
|
private 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) {
|
public static boolean isPalindrome(final SinglyLinkedList linkedList) {
|
||||||
boolean ret = true;
|
|
||||||
Stack<Integer> linkedListValues = new Stack<>();
|
Stack<Integer> linkedListValues = new Stack<>();
|
||||||
|
|
||||||
for (int i = 0; i < linkedList.size(); i++) {
|
for (final var x : linkedList) {
|
||||||
linkedListValues.push(linkedList.getNth(i));
|
linkedListValues.push(x);
|
||||||
}
|
}
|
||||||
|
|
||||||
for (int i = 0; i < linkedList.size(); i++) {
|
for (final var x : linkedList) {
|
||||||
if (linkedList.getNth(i) != linkedListValues.pop()) {
|
if (x != linkedListValues.pop()) {
|
||||||
ret = false;
|
return false;
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return ret;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -28,6 +28,17 @@ public class PalindromeSinglyLinkedListTest {
|
|||||||
assertTrue(PalindromeSinglyLinkedList.isPalindrome(exampleList));
|
assertTrue(PalindromeSinglyLinkedList.isPalindrome(exampleList));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testWithListWithOddLengthPositive2() {
|
||||||
|
var exampleList = new SinglyLinkedList();
|
||||||
|
exampleList.insert(3);
|
||||||
|
exampleList.insert(2);
|
||||||
|
exampleList.insert(1);
|
||||||
|
exampleList.insert(2);
|
||||||
|
exampleList.insert(3);
|
||||||
|
assertTrue(PalindromeSinglyLinkedList.isPalindrome(exampleList));
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testWithListWithEvenLengthPositive() {
|
public void testWithListWithEvenLengthPositive() {
|
||||||
var exampleList = new SinglyLinkedList();
|
var exampleList = new SinglyLinkedList();
|
||||||
|
Reference in New Issue
Block a user