class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
//辅助节点
ListNode dummy = new ListNode(-1);
dummy.next = head;
//链表长度
int len = 0;
ListNode cur = head;
while(cur != null){
++len;
cur = cur.next;
}
//短了
if(n > len) return head;
//移动要删除节点的前一个节点
n = len - n;
cur = dummy;
while(n > 0) {cur = cur.next;--n;}
//删除
cur.next = cur.next.next;
return dummy.next;
}
}
19. 删除链表的倒数第 N 个结点
最新推荐文章于 2024-05-13 20:40:44 发布