21.删除链表的倒数第N个结点
方法:计算链表长度
/**
* 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) {
ListNode dummy = new ListNode(0,head);
ListNode p = head;
int m = 0;
while(p != null){
p = p.next;
m++;
}
int x = m - n ;
ListNode q = dummy;
while(x > 0){
q = q.next;
x--;
}
q.next = q.next.next;
return dummy.next;
}
}