206. 反转链表
class Solution {
public:
ListNode* reverseList(ListNode* head) {
// //迭代法
// ListNode *pre = nullptr;
// ListNode *curr = head;
// while(curr){
// ListNode *next = curr -> next;
// curr -> next = pre;
// pre = curr;
// curr = next;
// }
// return pre;
//递归
if(!head || !head -> next){
return head;
}
ListNode *newhead = reverseList(head -> next);
head -> next -> next = head;
head -> next = nullptr;
return newhead;
}
};
234. 回文链表
1、快慢指针+翻转(可以实现进阶的要求,也就是说O(1)空间复杂度)
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(!head || !head->next) //表示如果head或者head->next是空的,则返回true
return 1;
ListNode *fast = head, *slow = head;
ListNode *p,*pre = NULL;
while(fast && fast->next){
p = slow;
slow = slow -> next;//慢指针
fast = fast -> next ->next;//快指针
p -> next = pre;//翻转
pre = p;
}
if(fast)
slow = slow -> next;//把慢指针移动到回文开始的地方
while(p){
if(p->val != slow->val)
return 0;
p = p -> next;
slow = slow -> next;
}
return 1;
}
};
2、栈
stack<int> s; //定义栈s
ListNode *p = head;
while(p){
s.push(p -> val);//把P的值加入栈s中
p = p -> next;
}
p = head;//把head赋值给P
while(p){
if(p -> val != s.top()){
return 0;
}
s.pop();//把栈上面的值pop出去
p = p -> next;
}
return 1;