19.删除链表的倒数第N个结点
注意:先声明一个头结点,它的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) {ListNode dummy = new ListNode(0,head);//声明一个头节点ListNode p = head;int count = 0;while(p!=null){count++;p = p.next;}int m = count - n ; //找到倒数第n个节点的前一个节点的索引ListNode q = dummy;while(m>=1){q = q.next;m--;}q.next = q.next.next;return dummy.next;}
}