題目一:在O(1)時間內(nèi)刪除鏈接節(jié)點(非尾節(jié)點)
思路:把下一個節(jié)點的內(nèi)容復(fù)制到需要刪除的節(jié)點上覆蓋原有的內(nèi)容即可偏形。如果刪除的是尾節(jié)點仅叫,則需順序遍歷完成刪除膏斤;如果刪除的鏈表中只有一個節(jié)點盅惜,則刪除之后中剩,需把節(jié)點設(shè)置為None.
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
node.val = node.next.val
node.next = node.next.next
題目二:刪除鏈表中重復(fù)的節(jié)點
在一個排序的鏈表中,存在重復(fù)的結(jié)點抒寂,請刪除該鏈表中重復(fù)的結(jié)點结啼,重復(fù)的結(jié)點不保留,返回鏈表頭指針屈芜。 例如郊愧,鏈表1->2->3->3->4->4->5 處理后為 1->2->5
思路:要刪除有序鏈表中所有的重復(fù)節(jié)點,而頭結(jié)點有可能就是重復(fù)節(jié)點井佑。這樣的比較好的解決方式就是新建頭結(jié)點属铁,然后往后遍歷,同樣的值就全部略過毅糟。
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteDuplication(self, pHead):
# write code here
if pHead is None:
return None
#創(chuàng)建一個新的頭結(jié)點root红选,因為可能pHead就是重復(fù)節(jié)點
root = ListNode(-1)
root.next = pHead
last = root
while pHead and pHead.next:
if pHead.val == pHead.next.val:
value = pHead.val
while pHead and value == pHead.val:
pHead = pHead.next
last.next = pHead
else:
last = pHead
pHead = pHead.next
return root.next