示例1:
输入: 1->2->2->1
输出: true
进阶你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
Java
解题思路1:栈。将链表全部入栈,然后一边出栈,一边重新遍历链表,比较两者元素,只要有一个不同则不是回文序列
public static boolean isPalindromeByAllStack(ListNode head) {
ListNode temp = head;
Stack<ListNode> stack = new Stack();
//先入栈
while(temp != null){
stack.push(temp);
temp = temp.next;
}
//再出栈遍历
while(head != null){
if(head != stack.pop()){
return false;
}
}
return true;
}
解题思路2:通过双指针法来判断。通过找到链表的中间节点然后把链表后半部分反转,再用后半部分反转的链表和前半部分一个个比较即可
public boolean isPalindrome(ListNode head) {
ListNode fast = head, slow = head;
//通过快慢指针找到中点
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
//如果fast不为空,说明链表的长度是奇数个
if (fast != null) {
slow = slow.next;
}
//反转后半部分链表
slow = reverse(slow);
fast = head;
while (slow != null) {
//然后比较,判断节点值是否相等
if (fast.val != slow.val)
return false;
fast = fast.next;
slow = slow.next;
}
return true;
}
//反转链表
public ListNode reverse(ListNode head) {
ListNode prev = null;
while (head != null) {
ListNode next = head.next;
head.next = prev;
prev = head;
head = next;
}
return prev;
}
python
遍历链表,把所有节点上的元素都存储到列表中,然后用双指针解决
def isPalindrome(self, head):
cur, length = head, 0
result = []
# 遍历链表,把所有节点上的元素都存储到列表 result 中
while cur is not None:
length += 1
result.append(cur.val)
cur = cur.next
# 定义2个指针,一个从头开始往后,另一个从最后开始往前
left, right = 0, length - 1
while left < right:
if result[left] != result[right]:
return False
left += 1
right -= 1
return True