删除链表倒数第n个节点
![](https://img2022.cnblogs.com/blog/1468919/202206/1468919-20220629204616869-934427470.png)
https://leetcode.cn/problems/SLwz0R/
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func removeNthFromEnd(head *ListNode, n int) *ListNode { //return twoPoint(head,n) return rev(head,n) //return revPlus(head,n) } //一、计算链表长度 // 1.计算链表长度 // 2.增加一个哑节点,遍历到倒数n+1的位置 func rev(head *ListNode,n int) *ListNode{ k:=0 tmp:=head now:=&ListNode{ Next:head, } for tmp!=nil{ k++ tmp=tmp.Next } cur:=now for i:=0;i<k-n;i++{ cur=cur.Next } cur.Next=cur.Next.Next return now.Next } //二、数组定位倒数第n个节点 // 1.存储所有节点 // 2.倒数n+1的节点就是nodes[len(nodes)-1-n] func revPlus(head *ListNode,n int) *ListNode{ now:=&ListNode{ Next:head, } var nums []*ListNode for tmp:=now;tmp!=nil;tmp=tmp.Next{ nums=append(nums,tmp) } pre:=nums[len(nums)-1-n] pre.Next=pre.Next.Next return now.Next } //三、双指针 // 1.两个指针,步伐相同 // 2.快指针先移动n步 // 3.两个指针一起移动,直到快指针为nil // 4.此时慢指针就是倒数n位置 func twoPoint(head *ListNode,n int) *ListNode{ first:=head now:=&ListNode{ Next:head, } second:=now for i:=0;i<n;i++{ first=first.Next } for first!=nil{ first=first.Next second=second.Next } second.Next=second.Next.Next return now.Next }
等风起的那一天,我已准备好一切