Leetcode Golang 19. Remove Nth Node From End of List.go

2019-04-12 11:18:19 浏览数 (1)

版权声明:原创勿转 https://cloud.tencent.com/developer/article/1412893

思路

快慢指针,快指针先前进n步,然后两个指针一起前进,当快指针走到末尾的时候,慢指针所在的位置,就是目标位置

需要注意判断空节点情况

code

代码语言:javascript复制
func removeNthFromEnd(head *ListNode, n int) *ListNode {
   cur := head
   last := head
   for i := 0; i < n; i   {
   	if cur.Next != nil {
   		cur = cur.Next
   	} else {
   		return head.Next
   	}
   }
   for cur.Next != nil {
   	cur = cur.Next
   	last = last.Next
   }
   last.Next = last.Next.Next
   return head
}

0 人点赞