LeetCode-234.Palindrome Linked List

来源:互联网 发布:幸福蓝海网络学 编辑:程序博客网 时间:2024/05/29 02:46

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;    }

不适用stack,把后半部分链表反转

/** * 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 || 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)            l1 = l1.next;        ListNode last=reverse(l1);        l1 = head;        l2 = last;        while (l2!=null)        {            if (l1.val != l2.val)            {                reverse(last);                return false;            }                l1 = l1.next;            l2 = l2.next;        }        reverse(last);        return true;    }        private ListNode reverse(ListNode head)    {        ListNode pre=null,next;        while (head != null)        {            next = head.next;            head.next = pre;            pre = head;            head = next;        }        return pre;    }}


0 0