fix/19: clean up code

This commit is contained in:
novahe
2021-05-16 17:48:21 +08:00
parent 851946dc9a
commit 5e77733f1a
2 changed files with 18 additions and 48 deletions

View File

@ -17,31 +17,18 @@ type ListNode = structures.ListNode
// 解法一
func removeNthFromEnd(head *ListNode, n int) *ListNode {
if head == nil {
return nil
}
var fast, slow *ListNode
fast = head
slow = head
step := 0
for i := 0; i < n; i++ {
// n maybe much larger than length of linklist
if fast.Next == nil && step < n-1 {
return head
dummyHead := &ListNode{Next: head}
preSlow, slow, fast := dummyHead, head, head
for fast != nil {
if n <= 0 {
preSlow = slow
slow = slow.Next
}
n--
fast = fast.Next
step++
}
if fast == nil {
head = head.Next
return head
}
for fast.Next != nil {
fast = fast.Next
slow = slow.Next
}
slow.Next = slow.Next.Next
return head
preSlow.Next = slow.Next
return dummyHead.Next
}
// 解法二