- 83. Remove Duplicates from Sorte
- leetcode:83. Remove Duplicates f
- 83. Remove Duplicates from Sorte
- 83. Remove Duplicates from Sorte
- 83. Remove Duplicates from Sorte
- 83. Remove Duplicates from Sorte
- 83. Remove Duplicates from Sorte
- 83. Remove Duplicates from Sorte
- 83. Remove Duplicates from Sorte
- 83. Remove Duplicates from Sorte
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
分析:看到题设我开始以为是数组去重问题,先想到的是设置两个指针并移动的思路。仔细一看是链表,考虑到链表删除节点还是比较容易的,只需要把next指针指向下一个节点即可,所以不需要设置两个指针。思路是设置一个指针a指向头结点,比较a和下一个节点b,如果相等就移除节点b;如果不等就把a指针指向b节点,继续向下遍历即可,代码如下
func deleteDuplicates(_ head: ListNode?) -> ListNode? {
guard let _ = head else {
return nil;
}
var temp:ListNode = head!;
while ((temp.next) != nil) {
if temp.val != temp.next?.val {
temp = temp.next!;
} else {
temp.next = temp.next?.next;
}
}
return head;
}
网友评论