HTMLify

LeetCode - Palindrome Linked List - Go
Views: 46 | Author: abh
/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */

/* Stack */
type Stack struct {
    values []int
    len int
}

func (self *Stack) push(n int) {
    self.values = append(self.values, n)
    self.len++
}

func (self *Stack) pop() int {
    e := self.values[self.len-1]
    self.values = self.values[:self.len-1]
    self.len--
    return e
}

func isPalindrome(head *ListNode) bool {
    var stack Stack
    var stack2 Stack
    for ;head!=nil; {
        stack.push(head.Val)
        head = head.Next
    }
    for ;stack.len>0; {
        e := stack.pop()
        if stack.len==stack2.len {
            break
        }
        stack2.push(e)
        if stack.len==stack2.len {
            break
		}
    }
    if stack.len == 0 {
        return true
    }
    for ;stack.len>0; {
        e1, e2 := stack.pop(), stack2.pop()
        if e1 != e2 {
            return false
        }
    }
    return true
}

Comments