Given a linked list, remove the nth node from the end of list and return its head.
For 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.
Note:
Given n will always be valid.
Try to do this in one pass.
删除倒数的第n个点。这道题加上桑一个链表大数的Java题,让我更加理解了Java链表处理的运用。
一般都是先声明一个头结点tail,tail.next 指向链表第一个节点,然后声明一个引用ptr指向tail,这个ptr用来操作这个链表,增删改查等,但是tail一直没变,所以最后可返回tail.next,返回为处理后链表的地址(也是首地址)。
头结点的意义就是为了统一处理空表和一般单链表的操作。避免出现空指针的异常
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public static ListNode removeNthFromEnd(ListNode head, int n) {
ListNode tail = new ListNode(0);
tail.next = head;
ListNode ptr = tail;
int len = 0;
while(ptr!=null) {
ptr = ptr.next;
len++;
}
len--;
len-=n;
ptr = tail;
int cnt = 0;
while(cnt!=len) {
ptr = ptr.next;
cnt++;
}
ptr.next = ptr.next.next;//不影响ptr.next.next后面的连接,头结点的意义也在于此
return tail.next;
}
}