【面试题】从链表尾部算起,删除第n个节点

polaris · · 2695 次点击
应该考虑只用一次循环来实现 用一个指针p保留当前节点i的前面n节点 每次迭代,p,i都叠加 当i是末尾时,删除p
#2
更多评论
```go type ListNode struct { Val int Next *ListNode } func removeNthFromEnd(head *ListNode, n int) *ListNode { if head != nil { // 获取长度 var hLen int for l := head; l != nil; l = l.Next { hLen++ } // 计算删除位置 n = hLen - n + 1 front := head now := head.Next for i := 2; i < n && now.Next != nil; i++ { front = now now = front.Next } front.Next = now.Next now = nil return head } return nil } ```
#1
单链表 ```go func removeNthFromEnd(head *NodeList, n int) *NodeList { if head == nil{ return nil } if n < 0 { return head } i, j := head, head z := 0 for ; i.Next != nil; i=i.Next{ if z < n+ 1 { z++ continue } j = j.Next } if(z > n){ j.Next = j.Next.Next } return head; } ```
#3