题目要求:
给你一个链表,删除链表的倒数第 n
**个结点,并且返回链表的头结点。
示例 1:
输入: head = [1,2,3,4,5], n = 2
输出: [1,2,3,5]
示例 2:
输入: head = [1], n = 1
输出: []
示例 3:
输入: head = [1,2], n = 1
输出: [1]
提示:
链表中结点的数目为sz
1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz
链接:https://leetcode.cn/problems/remove-nth-node-from-end-of-list/description/
解题思路
使用遍历计算出链表的长度l,之后使用for遍历到l-n,第l-n+1个元素就是需要删除的元素。
代码:
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func removeNthFromEnd(head *ListNode, n int) *ListNode {
l := 1
dummy := &ListNode{Next: head}
for head.Next != nil {
l++
head = head.Next
}
cur := dummy
for i := 0; i < l-n; i++ {
cur = cur.Next
}
cur.Next = cur.Next.Next
return dummy.Next
}