public class ListNode{
int val;
ListNode next;
//三种构造函数
public ListNode(){
}
public ListNode(int val){
this.val = val;
}
public ListNode(int val,ListNode next){
this.val = val;
this.next = next;
}
}
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
//新建虚拟头节点
ListNode dummyNode = new ListNode(0,head);
//快慢指针指向虚拟头节点
ListNode fast = dummyNode;
ListNode slow = dummyNode;
//令快慢指针相差n个节点
for(int i = 0;i<=n ; i ++){
fast = fast.next;
}
// 移动到应该删除的位置
while(fast != null){
fast = fast.next;
slow = slow.next;
}
// 删除,排除空指针异常
if (slow.next != null){
slow.next = slow.next.next;
}
return dummyNode.next;
}
}
同样是双指针的应用。
栈溢出通常是无限递归导致的。
//初始化的定义一定要=null,否则会空指针异常。
ListNode pre = null;