This notebook was prepared by [Donne Martin](http://donnemartin.com). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges).

Challenge Notebook

Problem: Determine if a linked list is a palindrome.

Constraints

  • Is a single character or number a palindrome?
    • No
  • Can we assume we already have a linked list class that can be used for this problem?
    • Yes

Test Cases

  • Empty list -> False
  • Single element list -> False
  • Two or more element list, not a palindrome -> False
  • General case: Palindrome with even length -> True
  • General case: Palindrome with odd length -> True

Algorithm

Refer to the Solution Notebook. If you are stuck and need a hint, the solution notebook's algorithm discussion might be a good place to start.

Code


In [ ]:
%run ../linked_list/linked_list.py
%load ../linked_list/linked_list.py

In [ ]:
class MyLinkedList(LinkedList):

    def is_palindrome(self):
        # TODO: Implement me
        pass

Unit Test

The following unit test is expected to fail until you solve the challenge.


In [ ]:
# %load test_palindrome.py
from nose.tools import assert_equal


class TestPalindrome(object):

    def test_palindrome(self):
        print('Test: Empty list')
        linked_list = MyLinkedList()
        assert_equal(linked_list.is_palindrome(), False)

        print('Test: Single element list')
        head = Node(1)
        linked_list = MyLinkedList(head)
        assert_equal(linked_list.is_palindrome(), False)

        print('Test: Two element list, not a palindrome')
        linked_list.append(2)
        assert_equal(linked_list.is_palindrome(), False)

        print('Test: General case: Palindrome with even length')
        head = Node('a')
        linked_list = MyLinkedList(head)
        linked_list.append('b')
        linked_list.append('b')
        linked_list.append('a')
        assert_equal(linked_list.is_palindrome(), True)

        print('Test: General case: Palindrome with odd length')
        head = Node(1)
        linked_list = MyLinkedList(head)
        linked_list.append(2)
        linked_list.append(3)
        linked_list.append(2)
        linked_list.append(1)
        assert_equal(linked_list.is_palindrome(), True)

        print('Success: test_palindrome')


def main():
    test = TestPalindrome()
    test.test_palindrome()


if __name__ == '__main__':
    main()

Solution Notebook

Review the Solution Notebook for a discussion on algorithms and code solutions.