题目截图
方法一:一次遍历(单指针)
因为该链表是已经排序好的,可以一次性遍历,直接将链表每个元素与之前元素重复的去掉。
利用cur指针指向头节点,然后开始遍历,如果cur与cur.next对应的元素相同,就让cur.next指向cur.next.next,即可删除该结点。遍历完成后返回头节点即可。
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
if not head:
return head
cur = head
while cur.next:
if cur.val == cur.next.val:
cur.next = cur.next.next
else:
cur = cur.next
return head
利用ListNode构建Linked_List
c