auto a = head; auto start = head; int n = 0; while(a){ n++; a = a->next; } if(n <= 1) returntrue;
a = head; for(int i = 0;i<n-n/2;i++){ a = a->next; } auto b = a->next;
for(int i = 0;i<n/2-1;i++){ auto c = b->next; b->next = a; a = b; b = c; } auto tail = a; bool success = true; for(int i = 0;i<n/2;i++){ if(a->val != start->val){ success = false; break; } a = a->next; start = start->next; } a = tail; b = a->next; for(int i = 0;i<n/2-1;i++){ auto c = b->next; b->next = a; a = b; b = c; } tail->next = NULL;
return success; }
3.环形链表
检查一个链表是否存在环
解决方案:快慢指针 快指针每次前进2步,慢指针一次前进1步。如果存在环,则快指针早晚会相遇。
1 2 3 4 5 6 7 8 9 10 11 12 13
boolhasCycle(ListNode *head){ if(!head||!head->next) returnfalse; auto s = head,f = head->next; while (f) { s = s->next; f = f->next; if(!f) returnfalse; f = f->next; if(s == f) returntrue; } returnfalse; }