Merge pull request #132 from NovaHe/fix/19

fix/19: clean up code
This commit is contained in:
halfrost
2021-05-17 01:22:55 +08:00
committed by GitHub
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
}
// 解法二

View File

@@ -52,7 +52,6 @@ Output: [1]
## 代码
```go
package leetcode
import (
@@ -72,31 +71,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
}
// 解法二
@@ -136,9 +122,6 @@ func removeNthFromEnd1(head *ListNode, n int) *ListNode {
}
return head
}
```