LeetCode-234.Palindrome Linked List

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

Given a singly linked list, determine if it is a palindrome.

Follow up:
Could you do it in O(n) time and O(1) space?

使用栈和快慢指针

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int x) { val = x; }
 * }
 */

public bool IsPalindrome(ListNode head) 
    {
        if (head == null || head.next == null)
            return true;
        ListNode l1 = head,l2=head;
        Stack<int> s = new Stack<int>();
        while (l2!=null&&l2.next!=null)
        {
            s.Push(l1.val);
            l1 = l1.next;
            l2 = l2.next.next;
        }
        if (l2 != null)//奇数个node
            l1 = l1.next;
        while (l1!=null)
        {
            if (l1.val != s.Pop())
                return false;
            l1 = l1.next;
        }
        return true;
    }


你可能感兴趣的:(LeetCode,stack)