题目描述
Given a singly linked list, determine if it is a palindrome.
Example 1:
Input: 1->2
Output: false
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindrome-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
代码
同143的处理,快慢指针将链表分为前后两条,后一条进行reverse操作后进行比对。此处reverse采用一边遍历一边改变指针的方法。
#include <iostream>
using namespace std;
/// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
/// Two Pointers to Reverse and Traverse
/// Time Complexity: O(n)
/// Space Complexity: O(1)
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(head == NULL || head->next == NULL)
return true;
ListNode* slow = head;
ListNode* fast = head;
while(fast->next != NULL && fast->next->next != NULL){
slow = slow->next;
fast = fast->next->next;
}
slow->next = reverse(slow->next);
slow = slow->next;
ListNode* cur = head;
while(slow != NULL){
if(cur->val != slow->val)
return false;
else{
slow = slow->next;
cur = cur->next;
}
}
return true;
}
private:
ListNode* reverse(ListNode* head){ //一边遍历一边改变指针
if(head == NULL || head->next == NULL)
return head;
ListNode* pre = head;
ListNode* cur = head->next;
ListNode* next = cur->next;
head->next = NULL;
while(true){
cur->next = pre;
pre = cur;
cur = next;
if(cur == NULL)
break;
next = cur->next;
}
return pre;
}
};
int main() {
return 0;
}
思路二(浅)
(移动过程中进行前半部分链表的翻转)
思想很很简单,用2个指针,一个low,一个fast,fast是low的2倍,所以可以达到2分链表的效果
,在移动指针时同时对前半部分链表进行反转。最后直接比较被分开的2个链表
因为不能改变当前slow的next,不然就无法跳到下一个元素,所以这里用pre和prepre实现指针的反转
时间复杂度:第一个循环O(n/2),第2个循环O(n/2)
public boolean isPalindrome(ListNode head) {
if(head == null || head.next == null) return true;
ListNode slow = head, fast = head.next, pre = null, prepre = null;
while(fast != null && fast.next != null) {
//反转前半段链表
pre = slow;
slow = slow.next;
fast = fast.next.next;
//先移动指针再来反转
pre.next = prepre;
prepre = pre;
}
ListNode p2 = slow.next;
slow.next = pre;
ListNode p1 = fast == null? slow.next : slow;
while(p1 != null) {
if(p1.val != p2.val)
return false;
p1 = p1.next;
p2 = p2.next;
}
return true;
}