void sumLinks(Node* list1, Node* list2) { if (list1 == NULL && list2 == NULL) return; int carry = 0; int val = 0; Node* l1 = list1; Node* l2 = list2; /// determine if a list is longer and if so, pad that list int l1Len = lenList(l1); int l2Len = lenList(l2); if (l1Len > l2Len) { padList(l2, l1Len - l2Len); } if (l2Len > l1Len) { padList(l1, l2Len - l1Len); } while (l1 || l2) { l1->data += carry; val = l1->data + l2->data; if (val > 9) { carry = 1; val = val - 10; } else { carry = 0; } l1->data = val; l1 = l1->next; l2 = l2->next; } /// if the final digit had a carry we need to add one to the end if (carry) { /// reset the head and find the last element l1 = list1; while (l1->next) { l1 = l1->next; } l1->next = new Node(); l1->next->data = 1; l1->next->next = nullptr; } }
ListNode* rotateRight(ListNode* head, int k) { if (head == nullptr) return head; int n = lenList(head); k = (n - k % n) % n; ListNode** prev = &head; for (int i = 0; i < k; i++) { prev = &(*prev)->next; } ListNode* new_head = *prev; *prev = nullptr; for (ListNode* i = new_head; i != nullptr; i = i->next) { prev = &i->next; } *prev = head; return new_head; }
ListNode* reverseKGroup(ListNode* head, int k) { ListNode* resHead = NULL; ListNode** tail = &resHead; int len = lenList(head); while (len >= k) { ListNode** nextTail = &head->next; for (int i = 0; i < k; i++) { auto next = head->next; head->next = *tail; *tail = head; head = next; } len -= k; tail = nextTail; } *tail = head; return resHead; }
int ll::lenList(node *curr,int len){ if(!curr) return len; curr=curr->next; return lenList(curr,len+1); }