题目描述

1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz

1、两次扫描

代码

/**
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode() {}
*     ListNode(int val) { this.val = val; }
*     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {

// // 方法1：两次扫描

int size = -1;

//第一次扫描  得到链表的长度size
while (cur.next != null){
cur = cur.next;
size++;
}
}
}


2、双指针

代码：

		ListNode dummyNode = new ListNode(0,head);//虚拟头节点

ListNode fast = head,slow = dummyNode;

for(int i=0;i<n;i++){
fast = fast.next;
}
while(fast != null){
fast = fast.next;
slow = slow.next;
}
//slow是倒数第n个节点的前一个
slow.next = slow.next.next; //删除

return dummyNode.next;


3、栈

代码

    //虚拟头节点
Stack<ListNode> s = new Stack<>();

ListNode cur = dummyNode;
while(cur != null){
s.push(cur);
cur = cur.next;
}

for(int i=0;i<n;i++){
s.pop();
}

ListNode pre = s.peek();//栈的最顶节点 -- 即倒数第n+1个节点
pre.next = pre.next.next;

return dummyNode.next;


02-03 868
03-25 1104
02-11 346
11-18 1209
04-09 41
01-13 11
04-10 9246
06-24 198
03-16 74