File tree Expand file tree Collapse file tree 2 files changed +48
-0
lines changed Expand file tree Collapse file tree 2 files changed +48
-0
lines changed Original file line number Diff line number Diff line change
1
+ Code
2
+ ====
3
+
4
+ ``` go
5
+ /* *
6
+ * Definition for singly-linked list.
7
+ * type ListNode struct {
8
+ * Val int
9
+ * Next *ListNode
10
+ * }
11
+ */
12
+ func mergeTwoLists (l1 *ListNode , l2 *ListNode ) *ListNode {
13
+ head := &ListNode{}
14
+ temp := head
15
+ for l1 != nil && l2 != nil {
16
+ if l1.Val < l2.Val {
17
+ head.Next = l1
18
+ l1 = l1.Next
19
+ head = head.Next
20
+ } else {
21
+ head.Next = l2
22
+ l2 = l2.Next
23
+ head = head.Next
24
+ }
25
+ }
26
+
27
+ if l1 != nil {
28
+ head.Next = l1
29
+ }
30
+
31
+ if l2 != nil {
32
+ head.Next = l2
33
+ }
34
+
35
+ return temp.Next
36
+ }
37
+ ```
38
+
39
+ Solution in mind
40
+ ================
41
+
42
+ - While lists are non empty, compare heads of both lists.
43
+ - Make merged list point to lower.
44
+ - Increment node pointer of lower.
45
+ - Move merge pointer to new node.
46
+ - If either list is empty and other is not, make merged pointer point to beginning of list.
Original file line number Diff line number Diff line change 19
19
20
20
- [ longest-common-prefix] ( Easy/longest-common-prefix.md )
21
21
22
+ - [ merge-two-sorted-lists] ( Easy/merge-two-sorted-lists.md )
23
+
22
24
Medium
23
25
------
24
26
You can’t perform that action at this time.
0 commit comments