leetcode 【 Remove Nth Node From End of List 】 python 实现

题目

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.

 

代码:oj在线测试通过 Runtime: 188 ms

 1 # Definition for singly-linked list.
 2 # class ListNode:
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.next = None
 6 
 7 class Solution:
 8     # @return a ListNode
 9     def removeNthFromEnd(self, head, n):
10         if head is None:
11             return head
12             
13         dummyhead = ListNode(0)
14         dummyhead.next = head
15         p1 = dummyhead
16         p2 = dummyhead
17         
18         for i in range(0,n):
19             p1 = p1.next
20         
21         while p1.next is not None:
22             p1 = p1.next
23             p2 = p2.next
24             if p1.next is None:
25                 break
26         
27         p2.next = p2.next.next
28         
29         return dummyhead.next

 

思路

Linked List基本都需要一个虚表头,这道题主要思路是双指针

让第一个指针p1先走n步,然后再让p1和p2一起走;当p1走到链表最后一个元素的时候,p2就走到了倒数n+1个元素的位置;这时p2.next向表尾方向跳一个。

注意下判断条件是p1.next is not None,因此在while循环中添加判断p1.next是否为None的保护判断。

再有就是注意一下special case的情况,小白我的习惯是在最开始就把这种case都判断出来;可能牺牲了代码的简洁性,有大神路过也请拍砖指点。

posted on 2014-12-26 14:21  承续缘  阅读(203)  评论(0编辑  收藏  举报

导航