您的位置:首页 > 其它

234. Palindrome Linked List

2016-06-25 10:36 330 查看
题目:https://leetcode.com/problems/palindrome-linked-list/

代码:

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isPalindrome(ListNode head) {
int length = getlength(head);
int[] cur = new int[length];
int index = 0;
while(head!=null)
{
cur[index++] = head.val;
head = head.next;
}
int i=0,j=length-1;
while(i<j)
{
if(cur[i]!=cur[j])
return false;
i++;j--;
}
return true;
}
public int getlength(ListNode head)
{
int length=0;
ListNode temp = head;
while(temp!=null)
{
length++;
temp = temp.next;
}
return length;
}
}
3ms
==============================用堆
/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isPalindrome(ListNode head) {
int length = getlength(head);
Stack<ListNode> temp = new Stack<>();
int flag = 0;
while(flag!=length/2&&head!=null)
{
temp.push(head);
head = head.next;
flag++;
}
if(length%2!=0)
head = head.next;
while(head!=null)
{
ListNode cur = temp.pop();
if(head.val!=cur.val)
return false;
head = head.next;
}
return true;
}
public int getlength(ListNode head)
{
int length=0;
ListNode temp = head;
while(temp!=null)
{
length++;
temp = temp.next;
}
return length;
}
}
4ms
====================dicuss里的一种解法: 翻转前半段
/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isPalindrome(ListNode head) {
// traverse the list once to count the number of elements and determine the midpoint
ListNode current = head;
int nodeCount = 0;
while (current != null) {
nodeCount++;
current = current.next;
}
int midCount = nodeCount/2;
// reverse the first half of the list
current = head;
ListNode previous = null;
ListNode temp = null;
for (int ii = 0; ii < midCount; ii++) {
temp = current.next;
current.next = previous;
previous = current;
current = temp;
}
// if there are an odd number of elements, skip the middle element
if (nodeCount % 2 == 1) {
current = current.next;
}
// compare the second half of the list to the reversed first half
// "previous" points to the head of the reversed first half
for (int jj = 0; jj < midCount; jj++) {
if (current.val != previous.val) {
return false;
} else {
current = current.next;
previous = previous.next;
}
}
return true;
}
}
1ms
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: