问题描述
https://leetcode.com/problems/remove-duplicates-from-sorted-list/
解决思路
如果当前节点的值和下一个节点的值相等,就将下个节点指向下下个节点;否则将当前节点指向下个节点。
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
//corner case
if(head == null) return head;
ListNode list = head;
while(list != null && list.next != null){
if(list.val == list.next.val){
list.next = list.next.next;
}else{
list = list.next;
}
}
return head;
}
}
复杂度分析
- 时间复杂度:O(n)
- 空间复杂度:O(1)