- 6.19
- to do
1] Remove Nth Node From End of List
unhandled special cases arise w/o help of dummy
ListNode* removeNthFromEnd(ListNode* head, int n) {
int len = 0;
for (ListNode* curr=head; curr; curr=curr->next) {
++len;
}
ListNode dummy(-1);
ListNode* finder = &dummy;
dummy.next = head;
for (int steps=0; steps<len-n; ++steps) {
finder = finder->next;
}
ListNode* remv = finder->next;
finder->next = remv->next;
delete(remv);
return dummy.next;
}
ListNode* swapPairs(ListNode* head) {
if (!head) return head;
ListNode dummy(-1);
dummy.next = head;
for ( ListNode* prev=&dummy, *l=prev->next, *r=l->next;
r;prev=l, l=prev->next, r=!l? nullptr : l->next) {
prev->next = r;
l->next = r->next;
r->next = l;
}
return dummy.next;
}
note: in for loop,
r=!l? nullptr : l->next
== redo w/o helper, try recursion ==
note while (--n>0) {} => body executes for n-1 times
ListNode* reverseList(ListNode* head) {
if (!head || !head->next) return head;
ListNode* newh = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return newh;
}
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode dummy(-1);
dummy.next=head;
int ct=0;
for (ListNode* prev=&dummy, *curr=prev->next; curr; curr = prev->next) {
int steps = k; //do k-1 times
while (curr && --steps>0) { curr = curr->next; }
if (!curr) break;
ListNode* nextGroup = curr->next;
curr->next = NULL;
ListNode* oldHead = prev->next;
prev->next = reverseList(oldHead);
oldHead->next = nextGroup;
prev = oldHead;
}
return dummy.next;
}
4] Copy List with Random Pointer
51% okiee :3
== redo w/ 分拆链表 ==
RandomListNode *copyRandomList(RandomListNode *head) {
RandomListNode dummy(-1);
dummy.next = head;
RandomListNode* newh = &dummy;
vector<RandomListNode*> newAddr;
unordered_map<RandomListNode*, int> addressToIndex;
// writer always points to the elem last written
int ct = 0;
for (RandomListNode* reader=head, *writer=newh; reader; reader=reader->next, writer=writer->next) {
writer->next = new RandomListNode(reader->label);
addressToIndex[reader] = (ct++);
newAddr.push_back(writer->next);
}
for (RandomListNode* reader=head, *writer=newh; reader; reader=reader->next, writer=writer->next) {
if (reader->random) {
writer->next->random = newAddr[ addressToIndex[reader->random] ];
}
}
return dummy.next;
}
- btw
5] Rectangle Area
or note if there's overlap, its area = [min(rightXcoords)-max(leftXcoords)] * [min(higherYcoords)-max(lowerYcoords)]
// make sure input x1l is the leftmost point
int overlapLen(int x1l, int x1r, int x2l, int x2r) {
if (x2l>=x1r) return 0;
if (x2r<=x1r) return x2r-x2l;
else return x1r-x2l;
}
int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
int xlen = A<=E? overlapLen(A, C, E, G) : overlapLen(E, G, A, C);
int ylen = B<=F? overlapLen(B, D, F, H) : overlapLen(F, H, B, D);
return (C-A)*(D-B) + (G-E)*(H-F) - (xlen*ylen);
}