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

119人阅读 评论(0)

## 题目描述

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.

/**
* 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 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;
}
}

/**
* 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;
}
}
predelete = predelete.next;
}
predelete.next = predelete.next.next;
return pre.next;
}
}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：24091次
• 积分：1354
• 等级：
• 排名：千里之外
• 原创：112篇
• 转载：30篇
• 译文：0篇
• 评论：4条
阅读排行
评论排行
最新评论