- to do
1.
- 5%..
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* dummy = new ListNode (-1);
ListNode* curr = dummy;
int carry = 0, sum = 0;
while (l1 || l2) {
if (!l1) {
sum = carry + l2->val;
l2 = l2->next;
} else if (!l2) {
sum = carry + l1->val;
l1 = l1->next;
} else {
sum = l1->val + l2->val + carry;
l1 = l1->next;
l2 = l2->next;
}
carry = sum/10;
curr->next = new ListNode(sum%10);
curr = curr->next;
}
if (carry) curr->next = new ListNode(carry);
return dummy->next;
}
-
simple iterative - JS
let reverseList = function(head) {
let prev = null;
while (head) {
let next = head.next;
head.next = prev;
prev = head;
head = next;
}
return prev;
};
-
simple recursive - JS
var reverseList = function(head) {
if (!head || !head.next) return head;
let newh = reverseList(head.next);
head.next.next = head;
head.next = null;
return newh;
};
2] Reverse Linked List II
note: avoid changing params I guess
ListNode* reverseBetween(ListNode* head, int m, int n) {
if (m >= n || !head) return head;
ListNode* dummy = new ListNode(-1);
dummy->next = head;
ListNode* lholder = dummy;
int ct = m;
while (--ct) lholder = lholder->next;
ListNode* prev = lholder->next, *curr = prev->next, *next = curr->next;
ct = n-m;
while (--ct) {
curr->next = prev;
prev = curr;
curr = next;
next = curr->next;
}
lholder->next->next = curr->next;
curr->next = prev;
lholder->next = curr;
return dummy->next;
}
or insert at head
var reverseBetween = function(head, m, n) {
// if (!head || m >= n) return head;
let dummy = new ListNode(-1);
dummy.next = head;
let prev = dummy;
for (let i = 0; i < m-1; ++i) {
prev = prev.next;
}
const lholder = prev;
prev = prev.next;
let curr = prev.next;
for (let i = m; i < n ; ++i) {
prev.next = curr.next;
curr.next = lholder.next;
lholder.next = curr;
curr = prev.next;
}
return dummy.next;
};
ListNode* partition(ListNode* head, int x) {
ListNode dummy(-1);
dummy.next = head;
ListNode dummy2(-1);
ListNode* tail2 = &dummy2;
ListNode* prev = &dummy;
ListNode* curr;
while (curr = prev->next) {
if (curr->val < x) {
prev->next = curr->next;
tail2->next = curr;
tail2 = curr;
} else {
prev = curr;
}
}
tail2->next = dummy.next;
return dummy2.next;
}
网友评论