题解 | #删除链表的倒数第n个节点#
删除链表的倒数第n个节点
https://www.nowcoder.com/practice/f95dcdafbde44b22a6d741baf71653f6
package main import . "nc_tools" /* * type ListNode struct{ * Val int * Next *ListNode * } */ /** * * @param head ListNode类 * @param n int整型 * @return ListNode类 */ func removeNthFromEnd(head *ListNode, n int) *ListNode { if n <= 0 { return head } var p *ListNode var q *ListNode var preP *ListNode for ; n > 0; n-- { if q == nil { q = head } else { q = q.Next } } for q != nil { preP = p if p == nil { p = head } else { p = p.Next } q = q.Next } if preP == nil { tmp := head.Next head.Next = nil return tmp } else { if p != nil { preP.Next = p.Next p.Next = nil } else { preP.Next = nil } return head } // write code here }