单向链表:
class ListNode{
public:
int val;
ListNode* next;
ListNode(int x) : val(x) {}
ListNode() = default;
};
递归反转单向链表:
反转全部:
ListNode* reverse_L(ListNode* head){
if(!head->next) return head;
ListNode* last = reverse_L(head->next);
head->next->next = head;
head->next = nullptr;
return last;
}
反转前n个节点:
ListNode_D* tmp;
ListNode_D* reverse_LN(ListNode_D* head, int n){
if(n == 1){
tmp = head->next;
return head;
}
ListNode_D* last = reverse_LN(head->next, n - 1);
head->next->next = head;
head->next = tmp;
return last;
}
反转[l,r]节点位置的链表:
ListNode_D* reverse_DLN(ListNode_D* head, int l, int r){
if(l == 1){
return reverse_LN(head, r);
}
head->next = reverse_DLN(head->next, l - 1, r - 1);
return head;
}
迭代翻转链表:
反转(l,r)区间的链表:
ListNode_D* reverse_a_b(ListNode_D* a, ListNode_D* b){
if(a == b || a->next == b) return a;
ListNode_D *pre, *cur, *nxt;
pre = a, cur = a->next;
do{
nxt = cur->next;
cur->next = pre;
pre = cur;
cur = nxt;
} while(cur != b);
a->next->next = b;
a->next = pre;
return a;
}
判断回文链表(递归):
递归法判断:
ListNode_D* leaf;
bool judge_D_palindrome(ListNode_D* right){
if(!right) return true;
bool res = judge_D_palindrome(right->next);
res = res && (leaf->val == right->val);
leaf = leaf->next;
return res;
}
bool judge_D(ListNode_D* head){
leaf = head;
return judge_D_palindrome(head);
}
快慢指针判别法:
bool judge_D_palindrom_double(ListNode_D* head){
ListNode_D *fast = head, *slow = head;
while(fast && fast->next){
fast = fast->next->next;
slow = slow->next;
}
if(fast) slow = slow->next;
ListNode_D *left = head;
ListNode_D *right = reverse_DL(slow);
while(right){
if(right->val != left->val) return false;
right = right->next;
left = left->next;
}
return true;
}