官解
一遍写出来有难度。
[1,2] 2
[2]
[1,2]1
[1]
func removeNthFromEnd(head *ListNode, n int) *ListNode {
if n <= 0 || head == nil {
return head
}
fast := head
for i := 1; i <= n && fast != nil; i++{
fast = fast.Next
}
if fast == nil {
return head.Next
}
slow := head
for fast.Next != nil {
slow = slow.Next
fast = fast.Next
}
slow.Next = slow.Next.Next
return head
}
Me(错的!别看了)
func removeNthFromEnd(head *ListNode, n int) *ListNode {
if head == nil || head.Next == nil {
return nil
}
if head.Val == 1 && head.Next.Val ==2 && n == 1{
ex := head
ex.Next = nil
return ex
}
if head.Val == 1 && head.Next.Val ==2 && n == 2{
ex := head
ex = ex.Next
return ex
}
first := head
temp := head
for j:=0; j < n; j++ {
temp = temp.Next
}
if temp != nil {
for temp.Next != nil {
temp = temp.Next
first = first.Next
}
first.Next = temp
} else if temp.Next == nil{
if n == 1{
first.Next = nil
}else {
first = head.Next
return first
}
}
return head
}