Given the head of a singly linked list, reverse the list, and return the reversed list.
Example 1:
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]
Example 2:
Input: head = [1,2]
Output: [2,1]
Example 3:
Input: head = []
Output: []
Constraints:
The number of nodes in the list is the range [0, 5000].
-5000 <= Node.val <= 5000
Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?
Solution
Approach #0: Iterative
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func reverseList(head *ListNode) *ListNode {
if head == nil {
return nil
}
cur := head
var prev *ListNode
for cur.Next != nil {
next := cur.Next
cur.Next = prev
prev = cur
cur = next
}
cur.Next = prev
return cur
}
Approach #1: Recursive
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func reverseList(head *ListNode) *ListNode {
if head == nil {
return head
}
return reverse(head, nil)
}
func reverse(cur, prev *ListNode) *ListNode {
next := cur.Next
cur.Next = prev
if next == nil {
return cur
} else {
return reverse(next, cur)
}
}
ransomNote and magazine consist of lowercase English letters.
Solution
Approach #0
func canConstruct(ransomNote string, magazine string) bool {
var m [26]int
for i := 0; i < len(magazine); i++ {
m[magazine[i]-'a']++
}
for i := 0; i < len(ransomNote); i++ {
m[ransomNote[i]-'a']--
if m[ransomNote[i]-'a'] < 0 {
return false
}
}
return true
}
A binary tree is uni-valued if every node in the tree has the same value.
Given the root of a binary tree, return true if the given tree is uni-valued, or false otherwise.
Example 1:
Input: root = [1,1,1,1,1,null,1]
Output: true
Example 2:
Input: root = [2,2,2,5,2]
Output: false
Constraints:
The number of nodes in the tree is in the range [1, 100].
0 <= Node.val < 100
Solution
Approach #0: BFS
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func isUnivalTree(root *TreeNode) bool {
queue := []*TreeNode{root}
v := root.Val
for i := 0; i < len(queue); i++ {
if queue[i].Val != v {
return false
}
if queue[i].Left != nil {
queue = append(queue, queue[i].Left)
}
if queue[i].Right != nil {
queue = append(queue, queue[i].Right)
}
}
return true
}
Approach #1: DFS
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func isUnivalTree(root *TreeNode) bool {
if root == nil {
return true
}
if root.Left != nil && root.Val != root.Left.Val || !isUnivalTree(root.Left) {
return false
}
if root.Right != nil && root.Val != root.Right.Val || !isUnivalTree(root.Right) {
return false
}
return true
}