Skip to content

Commit

Permalink
Q2.6: Palindrome: iterative implementation improvement
Browse files Browse the repository at this point in the history
  • Loading branch information
krlv committed Mar 15, 2019
1 parent 98cec66 commit e82c08f
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 9 deletions.
18 changes: 11 additions & 7 deletions ch02/06_palindrome.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,21 +27,25 @@ func IsPalindrome(node *Node) bool {
return true
}

// IsPalindromeList checks if the linked list is a palindrome
// IsPalindromeIterative checks if the linked list is a palindrome
// Implementation is based on Node.Len() method
// and uses a list as a storage for reverse values
func IsPalindromeList(node *Node) bool {
func IsPalindromeIterative(node *Node) bool {
nlen := node.Len()
revl := make([]int, nlen)
xlen := nlen / 2
revl := make([]int, xlen)

tail := node
for i := 0; i < nlen; i++ {
revl[nlen-1-i] = tail.data
for i := 0; i < xlen; i++ {
revl[xlen-1-i] = tail.data
tail = tail.next
}

tail = node
for i := 0; i < nlen; i++ {
if nlen%2 == 1 {
tail = tail.next
}

for i := 0; i < xlen; i++ {
if revl[i] != tail.data {
return false
}
Expand Down
4 changes: 2 additions & 2 deletions ch02/06_palindrome_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ func TestIsPalindromeList(t *testing.T) {
node.AppendToTail(3)
node.AppendToTail(4)

if IsPalindromeList(node) {
if IsPalindromeIterative(node) {
t.Error("Expected the linked list to be not a palindrome")
}

Expand All @@ -57,7 +57,7 @@ func TestIsPalindromeList(t *testing.T) {
node.AppendToTail(2)
node.AppendToTail(1)

if !IsPalindromeList(node) {
if !IsPalindromeIterative(node) {
t.Error("Expected the linked list to be a palindrome")
}
}
Expand Down

0 comments on commit e82c08f

Please sign in to comment.