您的位置:首页 > 其它

【Leetcode】Palindrome Linked List

2015-11-19 22:31 281 查看
题目链接: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?

思路:

1、用栈存储然后比较,无需改动链表结构,不过空间复杂度为O(n)

2、修改链表结构。找到中间结点,反转中间结点一边链表,然后中间结点两边链表比较。

算法1:

public boolean isPalindrome(ListNode head) {
Stack<Integer> stack = new Stack<Integer>();
ListNode p = head;
while (p != null) {
stack.push(p.val);
p = p.next;
}
p = head;
while (p != null) {
int tmp = stack.pop();
if (tmp != p.val) {
return false;
}
p = p.next;
}
return true;
}


算法2:

public int getListLength(ListNode head) {
int length = 0;
ListNode p = head;
while (p != null) {
length++;
p = p.next;
}
return length;
}

public ListNode reverseList(ListNode head) {
ListNode p = head, q, t;
if (p == null)
return head;
q = p.next;
while (q != null) {
t = q.next;// 保存当前要处理结点后面的一个结点
q.next = p;
p = q; // p是新链表头结点
q = t;
}
head.next = null;// 原头结点变成尾节点
head = p;
return head;
}

public boolean isPalindrome(ListNode head) {
if (head == null || head.next == null) {
return true;
}
int length = getListLength(head);
int i = length / 2;
ListNode p = head, l2 = null;
while (--i > 0)
p = p.next;
if (length % 2 == 0) {
l2 = p.next;
} else {
l2 = p.next.next;
}
p.next = null;

l2 = reverseList(l2);
while (head != null) {
if (head.val != l2.val) {
return false;
} else {
head = head.next;
l2 = l2.next;
}
}
return true;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: