83. 刪除排序鏈表中的重復(fù)元素
題解:
要刪除一個(gè)已排序鏈表中的所有重復(fù)元素,從而使每個(gè)元素只出現(xiàn)一次,我們可以使用一個(gè)指針來遍歷這個(gè)鏈表,同時(shí)比較當(dāng)前節(jié)點(diǎn)和它下一個(gè)節(jié)點(diǎn)的值。如果它們相等,我們就刪除下一個(gè)節(jié)點(diǎn),如果不相等,我們就移動指針。文章來源:http://www.zghlxwxcb.cn/news/detail-786846.html
注:本題使用的是虛擬頭節(jié)點(diǎn)文章來源地址http://www.zghlxwxcb.cn/news/detail-786846.html
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head or not head.next:
return head
dummy_head = ListNode(0)
dummy_head.next = head
cur = dummy_head.next
while cur and cur.next:
if cur.val == cur.next.val:
cur.next = cur.next.next
else:
cur = cur.next
return dummy_head.next
到了這里,關(guān)于leetcode-刪除排序鏈表中的重復(fù)元素的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!