LeetCode热题100道-Day02
- 两个指针分别指向两个链表,然后两个指针指向的值进行比较,选出较小的值,然后该指针向后移一位,循环这样操作即可得出有序链表
func mergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode {
res := &ListNode{}
p := res
for list1!=nil && list2!=nil {
if list1.Val<list2.Val {
p.Next = list1
list1 = list1.Next
} else {
p.Next = list2
list2 = list2.Next
}
p = p.Next
}
if list1!=nil {
p.Next = list1
}
if list2!=nil {
p.Next = list2
}
return res.Next
}
var res [][]int
var list []int
func permute(nums []int) [][]int {
res = [][]int{}
used := make([]bool, len(nums))
list = []int{}
tra(nums, used)
return res
}
func tra(nums []int, X []bool) {
if len(list)==len(nums) {
t := make([]int, len(list))
copy(t, list)
res = append(res, t)
return
}
for i:=0; i<len(nums); i++ {
if X[i] {
continue
}
list = append(list, nums[i])
X[i] = true
tra(nums, X)
X[i] = false
list = list[:len(list)-1]
}
}
- 定义指针c为当前点, p表示当前点的前一位, n为当前点的后一位,遍历调整当前点的Next即可
func reverseList(head *ListNode) *ListNode {
var p *ListNode
c := head
for c!=nil {
n := c.Next
c.Next = p
p = c
c = n
}
return p
}
func invertTree(root *TreeNode) *TreeNode {
tra(root)
return root
}
func tra(root *TreeNode) {
if root==nil {
return
}
tra(root.Left)
tra(root.Right)
temp := root.Left
root.Left = root.Right
root.Right = temp
}
func isPalindrome(head *ListNode) bool {
list := make([]int, 0)
for head!=nil {
list = append(list, head.Val)
head = head.Next
}
i := 0
j := len(list)-1
for i<j {
if list[i]!=list[j] {
return false
}
i++
j--
}
return true
}