一、题目
二、代码
思路:
- 遍历一遍链表,获取节点个数
- 引入虚拟节点,根据链表中倒数与正数的关系,确定正向的位置。(ps如果位置关系不清楚,可以自己画一下)
/**
* 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 head;
}
ListNode p = head;
int nodeNum = 0;
while(p != null){
nodeNum++;
p = p.next;
}
ListNode dummyHead = new ListNode(0);//虚拟节点
dummyHead.next = head;
int i = 0;
ListNode q =dummyHead;//注意q的指向
while(q.next != null && i <= nodeNum -n - 1){//注意第一个条件
q = q.next;
i++;
}
if(q.next != null){
q.next = q.next.next;
}
return dummyHead.next;
}
}