# LeetCode-remove-nth-node-from-end-of-list

## 题目描述

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.

/**
* 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) {
ListNode fast = head;
ListNode slow = head;
ListNode flag = new ListNode(0);
ListNode pre = flag;
pre.next = slow;
for(int i=1; i<n; i++){
fast = fast.next;
}
while(fast.next != null) {
fast = fast.next;
slow = slow.next;
pre = pre.next;
}
pre.next = slow.next;
return flag.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) {

ListNode pre = new ListNode(0);

ListNode predelete = pre;
for(int i=0; i<n; i++){
return null;
}
}
while(head != null) {
predelete = predelete.next;
}
predelete.next = predelete.next.next;
return pre.next;
}
}

• 本文已收录于以下专栏：

举报原因： 您举报文章：LeetCode-remove-nth-node-from-end-of-list 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)