问题描述:
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总是有效的,且一趟遍历完成。两个指针,两个指针相隔n-1,也就是前面那个指针先跑n步,随后一起向后走,那么前面那个指针先跑到尾节点的时候,后面那个指针就指向被指定删除节点的前一个节点,把这个节点的next引用指向后面的后面的话就算完成了。
代码(java):
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head == null){
return null;
}
ListNode front = head;
ListNode back = head;
for(int i = 0 ; i < n ; i++){
front = front.next;
}
if(front == null)
{
head = head.next;
front = null;
return head;
}
while(front.next != null){
front = front.next;
back = back.next;
}
back.next = back.next.next;
return head;
}
}