?LeetCode刷題實(shí)戰(zhàn)234:回文鏈表
Given the head of a singly linked list, return true if it is a palindrome.
示例
示例 1:
輸入: 1->2
輸出: false
示例 2:
輸入: 1->2->2->1
輸出: true
進(jìn)階:
你能否用 O(n) 時間復(fù)雜度和 O(1) 空間復(fù)雜度解決此題?
解題
class Solution {
public boolean isPalindrome(ListNode head) {
ListNode fast = head;
ListNode slow = head;
if (fast == null || fast.next == null) return true;
while (fast.next != null && fast.next.next != null) {
fast = fast.next.next;
slow = slow.next;
}
ListNode newHead = reverseList(slow.next);
while (newHead != null) {
if (head.val != newHead.val) return false;
head = head.next;
newHead = newHead.next;
}
return true;
}
//反轉(zhuǎn)鏈表函數(shù)--詳情請看前文
private ListNode reverseList(ListNode head) {
if (head.next == null) return head;
ListNode pre = null;
ListNode tmp;
while (head!= null) {
tmp = head.next;//tmp暫存當(dāng)前節(jié)點(diǎn)的下一個節(jié)點(diǎn)
head.next = pre;//當(dāng)前節(jié)點(diǎn)下一個指向pre
pre = head;//刷新pre
head = tmp;//刷新當(dāng)前節(jié)點(diǎn)為tmp
}
return pre;
}
}
LeetCode1-220題匯總,希望對你有點(diǎn)幫助!
LeetCode刷題實(shí)戰(zhàn)221:最大正方形
LeetCode刷題實(shí)戰(zhàn)222:完全二叉樹的節(jié)點(diǎn)個數(shù)
LeetCode刷題實(shí)戰(zhàn)223:矩形面積
LeetCode刷題實(shí)戰(zhàn)224:基本計算器
LeetCode刷題實(shí)戰(zhàn)225:用隊列實(shí)現(xiàn)棧
LeetCode刷題實(shí)戰(zhàn)226:翻轉(zhuǎn)二叉樹
LeetCode刷題實(shí)戰(zhàn)227:基本計算器 II
LeetCode刷題實(shí)戰(zhàn)228:匯總區(qū)間
LeetCode刷題實(shí)戰(zhàn)229:求眾數(shù) II
LeetCode刷題實(shí)戰(zhàn)230:二叉搜索樹中第K小的元素
LeetCode刷題實(shí)戰(zhàn)231:2的冪
LeetCode刷題實(shí)戰(zhàn)232:用棧實(shí)現(xiàn)隊列
LeetCode刷題實(shí)戰(zhàn)233:數(shù)字 1 的個數(shù)
