题目:
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?
这道题目不难,我考虑用两种方法来完成。
方法一:
考虑用两个ArrayList来存放数据,然后让某一个ArrayList反转其中存放的数据,最后再相互比较这两个ArrayList中的数据是否相同。
/**
*/ Definition for singly-linked list.
class ListNode
{
<span style="font-family: Arial, Helvetica, sans-serif;"> int val;</span>
<span style="font-family: Arial, Helvetica, sans-serif;"> ListNode next;</span>
ListNode(int x) { val = x; }
}
public class Solution
{
public static boolean isPalindrome(ListNode head)
{
boolean bool = false;
List list1 = new ArrayList();
List list2 = new ArrayList();
while(true)
{
if(head == null)
break;
else
{
list1.add(head.val);
list2.add(head.val);
head = head.next;
}
}
Collections.reverse(list2); //调用list自带的反转方法,特别快
if(list1.equals(list2))
bool = true;
return bool;
}
}
方法二:是考虑用一个stack(栈)来存储,也就是先将一个ArrayList中给的数据全都先进栈,然后再根据栈的特点,先进后出,依次从栈顶来输出数据和ArrayList中的从头开始的数据进行对比。
public static boolean isPalindrome(ListNode h)
{
boolean bool = true;
if(h == null || h.next == null)
return bool;
Stack<Integer> st = new Stack<Integer>();
ListNode h1 = h;
while(true)
{
st.push(h.val);
h = h.next;
if(h == null)
break;
}
while(h1 != null)
{
if(h1.val != st.peek())
{
bool = false;
break;
}
else
{
h1 = h1.next;
st.pop();
}
}
return bool;
}