mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
更新 0019.删除链表的倒数第N个节点 go版本
1、将原先代码中每次都需要获取慢指针前一个元素的方式修改成直接用慢指针进行元素的删除(代码便于理解) 2、调整代码格式
This commit is contained in:
@ -114,24 +114,28 @@ class Solution {
|
|||||||
```
|
```
|
||||||
Go:
|
Go:
|
||||||
```Go
|
```Go
|
||||||
|
/**
|
||||||
|
* Definition for singly-linked list.
|
||||||
|
* type ListNode struct {
|
||||||
|
* Val int
|
||||||
|
* Next *ListNode
|
||||||
|
* }
|
||||||
|
*/
|
||||||
func removeNthFromEnd(head *ListNode, n int) *ListNode {
|
func removeNthFromEnd(head *ListNode, n int) *ListNode {
|
||||||
result:=&ListNode{}
|
dummyHead := &ListNode{}
|
||||||
result.Next=head
|
dummyHead.Next = head
|
||||||
var pre *ListNode
|
cur := head
|
||||||
cur:=result
|
prev := dummyHead
|
||||||
|
|
||||||
i := 1
|
i := 1
|
||||||
for head!=nil{
|
for cur != nil {
|
||||||
if i>=n{
|
|
||||||
pre=cur
|
|
||||||
cur = cur.Next
|
cur = cur.Next
|
||||||
|
if i > n {
|
||||||
|
prev = prev.Next
|
||||||
}
|
}
|
||||||
head=head.Next
|
|
||||||
i++
|
i++
|
||||||
}
|
}
|
||||||
pre.Next=pre.Next.Next
|
prev.Next = prev.Next.Next
|
||||||
return result.Next
|
return dummyHead.Next
|
||||||
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user