版权声明:XiangYida https://blog.csdn.net/qq_36781505/article/details/83722691
19. Remove Nth Node From End of List
Given a linked list, remove the n-th node from the end of list and return its head.
Example:
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
嗯?这个题的意思就是给一个链表,然后删掉倒数的第某个位置,然后返回新链表,还是比较容易的
但是需要注意某些细节的地方。不想写了,睡觉。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode h=head;
int j=1;
while (null!=(h=h.next))j++;
if(j-n==0)return head.next;
if(j==1)return null;
h=head;
for (int i =1;i<(j-n); i++) {
if(null!=h.next)h=h.next;
else return head;
}
if(h.next!=null)h.next=h.next.next;
else h.next=null;
return head;
}
}