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

leetcode#19 Remove Nth Node From End of List

2015-06-03 20:01 423 查看

github链接

本题leetcode链接

题目描述

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个结点。关键是要求在遍历一趟的过程中完成。

问题在于如何找到要删除的那个结点,或者它的前一个结点。因为是单链表,只能从head的方向遍历。先遍历一遍,记录链表的长度,然后再计算出倒数第n个距离head的距离,再从头遍历到这个结点,这应该是可以的。或者使用两个指针,这两个指针进度不一,一个先一个后。第一个指针先从head开始走n的距离,第二个指针才从head开始走,等到第一个指针走到结尾的时候,因为第二个指针比它少走了n的距离,刚好指向倒数第n个结点。

链表删除结点有两种方法。

假设链表中结点i和在结点j的前面,k在结点j的后面,像这样

i -> j -> k

现在要删除结点j

当有一个指针ptr指向要删除的结点,也就是结点j时,先把j的下一个结点(假设不是null),也就是k.val赋给j.val,然后把k.next赋给j.next

当有一个指针ptr指向要删除的结点的前一个结点,也就是结点i时,直接
i.next = i.next.next
就行了

代码实现(JAVA)

public class RemoveNthNodeFromEndOfLinkList {
public ListNode removeNthFromEnd(ListNode head, int n) {

//特殊用例
if(head.next == null || head == null)
return null;
if (n  == 1) {
ListNode temp = head;
while(temp.next.next != null) {
temp = temp.next;
}
temp.next = temp.next.next;
return head;
}

ListNode pre,post;
pre = post = head;
//准备工作, 把post指针指向第n-1个结点
while(n>0) {
post = post.next;
n--;
}
//把pre指针指向倒数第n个结点
while(post != null) {
post = post.next;
pre = pre.next;
}
pre.val = pre.next.val;
pre.next = pre.next.next;

return head;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode linkedlist 算法