原题链接:83.Remove Duplicates from Sorted List
【思路】
思路很简单,逐一比较相邻两个节点的值,当遇到相同的值时,就将后一个节点从链表中移去:
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode dummyHead = head;
while (head != null && head.next != null) {
if (head.val == head.next.val) head.next = head.next.next;
else head = head.next;
}
return dummyHead;
}
}
164 / 164 test cases passed. Runtime:
1 ms Your runtime beats 16.98% of javasubmissions.
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
p = head
while p != None and p.next != None :
if p.val == p.next.val :
p.next = p.next.next
else :
p = p.next
return head
164 / 164
test cases passed. Runtime: 72 ms Your runtime beats 33.61% of pythonsubmissions.