您的位置:首页 > Web前端 > Node.js

LeetCode 019 Remove Nth Node From End of List

2014-03-29 10:57 459 查看
题目

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个给删除。

思路

1 条件中,n永远合法,所以减少了错误判断所需的内容。

2 第一次last,先记录 离head n的节点在哪。

3 第二次,保留一个pre , pre 和 last同时前进,这样,当last指向最后一个节点的时候,pre正好是所要删除的节点的前一个节点。

4 进行删除操作。

代码

public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head==null){
return null;
}
ListNode dummy = new ListNode(Integer.MIN_VALUE);
dummy.next = head;
ListNode last =dummy;
for(int i=0;i<n;i++){
last = last.next;
}
ListNode pre = dummy;
while(last.next!=null){
last=last.next;
pre=pre.next;
}
pre.next = pre.next.next;
return dummy.next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 面试笔试