interview-preparation / what-we-do

0 stars 8 forks source link

[Linked Lists] interview questions #6 #54

Closed rygh4775 closed 5 years ago

rygh4775 commented 5 years ago

Palindrome: Implement a function to check if a linked list is a palindrome.

GyuminLee commented 5 years ago
    public boolean isPalindrome(LinkedListNode head) {
        boolean isPalindrome = true;

        LinkedListNode original = head;
        LinkedListNode reverse = original;
        reverse.next = null;

        //making a reversed linked list
        while (original != null) {
            LinkedListNode reversePrev = original.next;
            reversePrev.next = reverse;

            reverse = reversePrev;
            original = original.next;
        }

        //checking isPalindrome
        LinkedListNode forward = head;

        while(reverse != null) {
            if(reverse.value != forward.value) {
                isPalindrome = false;
            }
            forward = forward.next;
            reverse = reverse.next;
        }

        return isPalindrome;
    }
GyuminLee commented 5 years ago

간단히 생각하여 reverse시키는 것을 써 봤는데 recursion을 사용하는 등 굉장히 흥미로운 답안이 많았습니다. 꼭 한번 해봐야 할 것 같습니다 :)