1: /**
2: * Definition for singly-linked list.
3: * struct ListNode {
4: * int val;
5: * ListNode *next;
6: * ListNode(int x) : val(x), next(NULL) {}
7: * };
8: */
9: class Solution {
10: public:
11: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
12: ListNode *dummy = new ListNode(-1);
13: ListNode *cur = dummy;
14: while (l1 && l2) {
15: if (l1->val < l2->val) { cur->next = l1; l1 = l1->next; }
16: else { cur->next = l2; l2 = l2->next; }
17: cur = cur->next;
18: }
19: if (l1) cur->next = l1;
20: if (l2) cur->next = l2;
21: cur = dummy->next;
22: delete dummy;
23: return cur;
24: }
25: };
Showing posts with label merge list. Show all posts
Showing posts with label merge list. Show all posts
Saturday, August 6, 2016
21. Merge Two Sorted Lists
Well, this is a real easy one.
Sunday, July 3, 2016
143. Reorder List
Three steps:
(1) cut into two lists (note the first list must be longer or equal to the second list).
(2) reverse the second list.
(3) merge the two lists.
(1) cut into two lists (note the first list must be longer or equal to the second list).
(2) reverse the second list.
(3) merge the two lists.
1: /**
2: * Definition for singly-linked list.
3: * struct ListNode {
4: * int val;
5: * ListNode *next;
6: * ListNode(int x) : val(x), next(NULL) {}
7: * };
8: */
9: class Solution {
10: public:
11: void reorderList(ListNode* head) {
12: if (head == NULL || head->next == NULL) return;
13: int count = countList(head);
14: count = (count + 1) / 2;
15: ListNode *prev = NULL, *cur = head;
16: while (count) {
17: count--;
18: prev = cur;
19: cur = cur->next;
20: }
21: prev->next = NULL;
22: ListNode *l1 = head;
23: ListNode *l2 = reverseList(cur);
24: while (l2) {
25: ListNode *tmp = l2->next;
26: l2->next = l1->next;
27: l1->next = l2;
28: l1 = l2->next;
29: l2 = tmp;
30: }
31: return;
32: }
33: int countList(ListNode* head) {
34: int count = 0;
35: while (head) {
36: count++;
37: head = head->next;
38: }
39: return count;
40: }
41: ListNode *reverseList(ListNode *head) {
42: ListNode *dummy = new ListNode(-1);
43: ListNode *cur = head;
44: while (cur) {
45: ListNode *tmp = cur;
46: cur = cur->next;
47: tmp->next = dummy->next;
48: dummy->next = tmp;
49: }
50: head = dummy->next;
51: delete dummy;
52: return head;
53: }
54: };
Subscribe to:
Posts (Atom)