leetcode83 Remove Duplicates from Sorted List

 1 """
 2 Given a sorted linked list, delete all duplicates such that each element appear only once.
 3 Example 1:
 4 Input: 1->1->2
 5 Output: 1->2
 6 Example 2:
 7 Input: 1->1->2->3->3
 8 Output: 1->2->3
 9 """
10 """
11 删除链表结点,操作这类的题,一般需要定义两个指针
12 分别指向head 和 head.next 然后画图总结规律
13 """
14 class ListNode:
15     def __init__(self, x):
16         self.val = x
17         self.next = None
18 
19 class Solution:
20     def deleteDuplicates(self, head):
21         if head == None:
22             return head
23         p = head
24         q = head.next
25         while q:
26             if p.val == q.val:
27                 p.next = q.next
28                 q = p.next
29             else:
30                 p = p.next
31                 q = q.next
32         return head

猜你喜欢

转载自www.cnblogs.com/yawenw/p/12273841.html