Remove Nth Node From End of List

https://leetcode.com/problems/remove-nth-node-from-end-of-list/

Remove Nth Node From End of List

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个结点。

倒数如何实现?利用dummy结点和两个指针p1和p2,p1先行n步,然后p1和p2再一起走,当p1.next为空时即走完整个链表时,p2.next即为要删除的倒数第n个结点。

(设链表总共M个结点,需要找到倒数第n个,那么p2就需要正序走并经过M-n个结点,下一个就是所需的倒数第n个结点,这正序的M-n步怎么控制,就是通过p1这个指针)

 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     # @param {ListNode} head
 9     # @param {integer} n
10     # @return {ListNode}
11     def removeNthFromEnd(self, head, n):
12         dummy=ListNode(0)
13         dummy.next=head
14         p1=p2=dummy                      #p1,p2同时dummy出发
15         for i in range(n):               #p1先走n步
16             p1=p1.next
17         while p1.next:                   #p1,p2同时走,直到p1走完链表
18             p1=p1.next
19             p2=p2.next
20         p2.next=p2.next.next             #删去此时的p2.next
21         return dummy.next

 

posted @ 2015-06-30 10:01  小榛子  阅读(122)  评论(0编辑  收藏  举报