判断一个链表是否为回文结构
快慢指针+栈(先进后出)
快慢指针:找到链表中点;将前半段入栈,然后一个一个出栈与后半段比较
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
#include <cstddef>
class Solution {
public:
/**
* @param head ListNode类 the head
* @return bool布尔型
*/
bool isPail(ListNode* head) {
// 快慢指针+栈
if(!head || !head->next) return true;
stack<int> s;
s.push(head->val);
ListNode *slow=head, *fast=head;
while(fast->next && fast->next->next){
slow=slow->next;
fast=fast->next->next;
s.push(slow->val);
}
if(fast->next==NULL) s.pop();//如果奇数个数(先pop出中间的元素)
int tmp;
while(slow->next){
slow=slow->next;
tmp=s.top();
s.pop();
if(tmp!=slow->val) return false;
}
return true;
}
};
链表的奇偶重排
奇数位单链表(头结点为原链表头结点),偶数位单链表,偶数位头结点
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
* @param head ListNode类
* @return ListNode类
*/
ListNode* oddEvenList(ListNode* head) {
// write code here
if(!head || !head->next) return head;
ListNode *odd=head, *even=head->next, *h_even=even;
while(even && even->next){
odd->next=even->next;
odd=odd->next;
even->next=odd->next;
even=even->next;
}
odd->next=h_even;
return head;
}
};
删除有序链表中重复的元素-I
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
#include <cmath>
class Solution {
public:
/**
* @param head ListNode类
* @return ListNode类
*/
ListNode* deleteDuplicates(ListNode* head) {
if(!head || !head->next) return head;
ListNode *p=head;
while(p && p->next){
if(p->val==p->next->val){
ListNode *temp=p->next;
p->next=p->next->next;
delete temp;
}else p=p->next;
}
return head;
}
};
删除有序链表中重复的元素-II
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
/**
* @param head ListNode类
* @return ListNode类
*/
ListNode* deleteDuplicates(ListNode* head) {
if(!head || !head->next) return head;
ListNode* dummy = new ListNode(-1);
dummy->next = head;
ListNode* q = dummy; //q指向新链表的最后一个节点
ListNode* pre = head;
ListNode* p = head->next;
while(p != NULL){
while(p != NULL && p->val == pre->val){
p = p->next;
} //直到p指向第一个与pre不同的节点
if(p == pre->next){ //指向相邻两节点,非重复元素,三个指针后移一位
q->next = pre;
q = q->next;
pre = pre->next;
p = p->next;
}else if(p != NULL){//不相邻
pre = p;
p = p->next;
}else q->next = p;
}
if(pre->next == NULL){ //pre指向最后一个节点
q->next = pre;
}
return dummy->next;
}
};