Skip to content

Commit 52e92d3

Browse files
committed
add code to readme.md
1 parent b4a7974 commit 52e92d3

File tree

1 file changed

+20
-1
lines changed
  • src/0019.Remove-Nth-Node-From-End-of-List

1 file changed

+20
-1
lines changed

src/0019.Remove-Nth-Node-From-End-of-List/README.md

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,26 @@ Could you do this in one pass?
3131
> 我的解法是利用双指针,这两个指针相差 n 个元素,当后面的指针扫到链表末尾的时候,自然它前面的那个指针所指向的下一个元素就是要删除的元素,即 pre.next = pre.next.next;,但是如果一开始后面的指针指向的为空,此时代表的意思就是要删除第一个元素,即 head = head.next;。
3232
3333
```go
34-
34+
func removeNthFromEnd(head *ListNode, n int) *ListNode {
35+
fastNode := head
36+
slowNode := head
37+
for n > 0 {
38+
fastNode = fastNode.Next
39+
n--
40+
}
41+
42+
if fastNode != nil {
43+
for fastNode.Next != nil {
44+
fastNode = fastNode.Next
45+
slowNode = slowNode.Next
46+
}
47+
slowNode.Next = slowNode.Next.Next
48+
49+
} else {
50+
head = head.Next
51+
}
52+
return head
53+
}
3554
```
3655

3756
### 思路2

0 commit comments

Comments
 (0)