/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public bool IsPalindrome(ListNode head) {
        if (head == null)
            {
                return true;
            }
            else
            {
                Queue<int> Q = new Queue<int>();
                Stack<int> S = new Stack<int>();

                do
                {
                    Q.Enqueue(head.val);
                    S.Push(head.val);

                    head = head.next;
                }
                while (head != null);

                var len = S.Count;

                for (int i = 0; i < len; i++)
                {
                    var s = S.Pop();
                    var q = Q.Dequeue();
                    if (s != q)
                    {
                        return false;
                    }
                }
                return true;
            }
    }
}

https://leetcode.com/problems/palindrome-linked-list/#/description

 

补充一个python的实现:

 1 class Solution:
 2     def isPalindrome(self, head: ListNode) -> bool:
 3         lists = []
 4         while head != None:
 5             lists.append(head.val)
 6             head = head.next
 7         i,j = 0,len(lists)-1
 8         while i < j:
 9             if lists[i] != lists[j]:
10                 return False
11             i += 1
12             j -= 1
13         return True

 

posted on 2017-04-24 22:16  Sempron2800+  阅读(131)  评论(0编辑  收藏  举报