题目:
Given a sorted linked list, delete all duplicates such that each element appear only once.
Example 1:
Input: 1->1->2 Output: 1->2
Example 2:
Input: 1->1->2->3->3 Output: 1->2->3
代码:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
now = head
while now:
nxt = now.next
if nxt and nxt.val == now.val:
now.next=nxt.next
del(nxt)
else:
now=nxt
return head
分析:该题是将链表中重复的元素删除。需要对比当前节点的值和下一节点的值,如果下一节点为空或者值不相同,则将节点向后移动一个节点,如果下一节点不为空且与这一节点相同,则删除下一节点,将该节点的下一节点设置成下下节点。