题解 | #删除链表的倒数第n个节点#
删除链表的倒数第n个节点
https://www.nowcoder.com/practice/f95dcdafbde44b22a6d741baf71653f6
方法一:循环
方法二:递归
思路,首相找出链表的深度,然后根据n所在的位置找出要踢出的数据
注意:
1引用传递的问题,方法中只是传递的引用,如果引用值发生变化,ok.如果引用被指向另一个引用则会丢失原有数据
所以,要么是对象类型,通过对象传递,值改变
import java.util.*; import java.util.Stack; import java.util.concurrent.atomic.*; public class Solution { /** * * @param head ListNode类 * @param n int整型 * @return ListNode类 */ public ListNode removeNthFromEnd (ListNode head, int n) { AtomicInteger lineDeep = new AtomicInteger(0); dealHead(head, lineDeep); ListNode up = new ListNode(0); up.next = head; dealHead2(head, up, lineDeep, n); return up.next; } public void dealHead2(ListNode head, ListNode up, AtomicInteger lineDeep, Integer n) { int get = lineDeep.get(); if (get != n) { ListNode node = head.next; up.next = head; ListNode npNew = up.next; if (null != node) { lineDeep.decrementAndGet(); dealHead2(node, npNew, lineDeep, n); } } else { if (null == head.next) { up.next = null; } else { up.next = head.next; } } } public void dealHead(ListNode head, AtomicInteger lineDeep) { ListNode next = head.next; lineDeep.addAndGet(1); if (null != next ) { dealHead(next, lineDeep); } } }