19-Remove-Nth-Node-From-End-of-List
0x0 题目详情
0x1 解题思路
0x2 代码实现
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head==null){
return null;
}
//这里设置了头节点,方便指针移动
ListNode dummy=new ListNode(-1);
dummy.next=head;
ListNode current=dummy;
ListNode pre=dummy;
int step=n;
while(step>0){
current=current.next;
step--;
}
while(current.next!=null){
pre=pre.next;
current=current.next;
}
pre.next=pre.next.next;
return dummy.next;
}
}0x3 课后总结
Last updated