题目来源:
https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/
题意分析:
给你定一个排好序的链表,将所有重复的节点去掉。比如:给出1->2->3->3->4->4->5
, 返回 1->2->5
.
题目思路:
这里考的是链表的操作,判断时候有重复的节点,有就直接移到下一位就可以了。
代码(Python):
1 # Definition for singly-linked list. 2 # class ListNode(object): 3 # def __init__(self, x): 4 # self.val = x 5 # self.next = None 6 7 class Solution(object): 8 def deleteDuplicates(self, head): 9 """ 10 :type head: ListNode 11 :rtype: ListNode 12 """ 13 if head == None or head.next == None: 14 return head 15 ans = ListNode(-1) 16 ans.next,p = head,ans 17 tmp = p.next 18 while p.next: 19 while tmp.next and tmp.next.val == p.next.val: 20 tmp = tmp.next 21 if tmp == p.next: 22 p = p.next 23 tmp = p.next 24 else: 25 p.next = tmp.next 26 return ans.next 27