http://www.lintcode.com/zh-cn/problem/delete-node-in-the-middle-of-singly-linked-list/
给定一个单链表中的一个等待被删除的节点(非表头或表尾)。请在在O(1)时间复杂度删除该链表节点。
样例
Linked list is 1->2->3->4, and given node 3, delete the node in place 1->2->4
标签
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param: node: the node in the list should be deletedt
@return: nothing
"""
def deleteNode(self, node):
# write your code here
if node.val != None:
node.val = node.next.val
node.next=node.next.next
http://www.lintcode.com/zh-cn/problem/remove-nth-node-from-end-of-list/
定一个链表,删除链表中倒数第n个节点,返回链表的头节点。
注意事项
链表中的节点个数大于等于n
样例
给出链表1->2->3->4->5->null和 n = 2.
删除倒数第二个节点之后,这个链表将变成1->2->3->5->null.
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param: head: The first node of linked list.
@param: n: An integer
@return: The head of linked list.
"""
def removeNthFromEnd(self, head, n):
# write your code here
if head is None or n==0:return head
first ,dao_n = head ,head
for i in range(n):
first = first.next
#如果first为None,则倒数第n个节点是第一个,删除第一个即可
if first is None:
return dao_n.next
#直到first.next为None,dao_n可以删除节点了
while first.next:
dao_n = dao_n.next
first = first.next
#删除节点
dao_n.next = dao_n.next.next
return head