From e82c08f9afef904a946eadb72f83bf6a5c7c44c6 Mon Sep 17 00:00:00 2001 From: krlv Date: Thu, 14 Mar 2019 19:01:34 -0700 Subject: [PATCH] Q2.6: Palindrome: iterative implementation improvement --- ch02/06_palindrome.go | 18 +++++++++++------- ch02/06_palindrome_test.go | 4 ++-- 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/ch02/06_palindrome.go b/ch02/06_palindrome.go index 0a3bc89..1d19eaf 100644 --- a/ch02/06_palindrome.go +++ b/ch02/06_palindrome.go @@ -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 } diff --git a/ch02/06_palindrome_test.go b/ch02/06_palindrome_test.go index e3e4e71..e443880 100644 --- a/ch02/06_palindrome_test.go +++ b/ch02/06_palindrome_test.go @@ -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") } @@ -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") } }