Leetcode 19. 删除链表的倒数第 N 个结点
阿里云国内75折 回扣 微信号:monov8 |
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6 |
/**
* 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) {
int len=length(head);
ListNode dummy=new ListNode(0);
dummy.next=head;
ListNode cur=dummy;
for(int i=0;i<len-n;i++) cur=cur.next;
cur.next=cur.next.next;
return dummy.next;
}
public int length(ListNode head){
int len=0;
while(head!=null){
head=head.next;
len++;
}
return len;
}
}