Day 16
题目:删除排序链表中的重复元素
leetcode链接:删除排序链表中的重复元素
要点:快慢双指针
1、Java
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null) return head;
ListNode slow = head;
ListNode fast = head;
while(fast != null){
if(slow.val != fast.val){
slow.next = fast;
slow = fast;
}
fast = fast.next;
}
// 断开与后面重复的元素
slow.next = null;
return head;
}
}
2、python
class Solution:
def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head == None:
return head
slow = head
fast = head
while fast != None:
if slow.val != fast.val:
slow.next = fast
slow = fast
fast = fast.next
slow.next = None
return head