首页 > 其他 > 详细

Remove Nth Node From End of List

时间:2014-08-29 19:40:58      阅读:205      评论:0      收藏:0      [点我收藏+]
# Definition for singly-linked list.
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None
class Solution:
    # @return a ListNode
    def removeNthFromEnd(self, head, n):
        if head==None:
            return 
        pre_head=ListNode(0)
        pre_head.next=head
        ruler_end=pre_head
        ruler_head=pre_head
        while n:
            ruler_end=ruler_end.next
            n-=1
        while ruler_end.next!=None :
            ruler_end=ruler_end.next
            ruler_head=ruler_head.next
        temp=ruler_head.next
        ruler_head.next=temp.next
        return pre_head.next

 不知道链表的结尾在哪里的情况下,删除从结尾算起的第n个节点,要求只遍历一趟的情况下完成。

这道题目确实没想到解决方法,参考别人的。值得记住。

知道是从结尾算起的第n个节点,那么建立一个距离为n+1的“尺子”,“尺子”的一端到了链表的末尾,那么另一端就是在要删除哪个节点的前一个。

 

Remove Nth Node From End of List

原文:http://www.cnblogs.com/iois/p/3945536.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!