您的位置:首页 > 其它

LeetCode-234.Palindrome Linked List

2016-05-15 22:51 411 查看
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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode stack