题目描述:
Given a linked list, remove the n th 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个结点,可以使用快慢指针,由于题目有说给的n是有效的,所以先让faster走n步,绝对是可以达到的
- 然后如果此时faster已经为空,则删除头结点,返回头结点
- 如果不为空,快慢指针就一起往后走,直到遇到faster的下一个为空
- faster的next为空,此时删除的是slow的下一个,所以slow.next = slow.next.next;
代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head ==null|| head.next==null)
return null;
ListNode faster = head;
ListNode slow = head;
for(int i=0;i<n;i++){
faster = faster.next;
}
if(faster ==null){
head = head.next;
return head;
}
while(faster.next!=null){
slow = slow.next;
faster = faster.next;
}
slow.next = slow.next.next;
return head;
}
}