思路很简单,就是将链表反转,定义一个头指针t,让t遍历到要删除的节点的上一个节点,修改下一个为下下个。
假设我们要删除的是倒数第三个节点,如图:
但是这样有一种情况解决不了,那就是删除最后一个节点,因为链表反转后,相当于第一个节点,他没有上一个节点。所以我们应该单独解决:node = node.next;
代码奉上
/**
* Definition for singly-linked list.
* 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) {
if(head.next == null) return null;
ListNode node = reverse(head);
ListNode t = node;
for(int i = 1;i < n;i++){
t = t.next;
}
if(n == 1) node = node.next;
else
t.next = t.next.next;
ListNode res = reverse(node);
return res;
}
public ListNode reverse(ListNode head){
if(head == null) return null;
ListNode cur = head;
ListNode temp = null;
ListNode pre = null;
while(cur !=null){
temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}
}