tag 重复数据
线性表
单链表
思想
- 使用双指针法,同时标记前后两个数据,这里有一点,如果只有一个数据,那就直接返回数组就好啦
- 如果数组的长度大于等于2
- 使用first标记第一个数据,second标记第二个数据
- 如果first.data != second.data ,那么first和second就可以同时前进
- 如果first.data == second.data, 就不断的使second前进,直到找到一个first.data != second.data
1. first前进一格,因为first和当初前面的second是重复数据,而first本身不重复,所以first前进一格
2. first.data = second.data
- 重复1-3直到second达到最末尾,现在从第一个到first标记的数据都是不重复的数据,也就是说first就是不重复数据的最终标记
代码
ListNode first = head;
if(first == null)
return head;
ListNode second = first.next;
while(second != null) {
if(second.val != first.val) {
first = first.next;
first.val = second.val;
}
second = second.next;
}
first.next = null;
return head;
总结
- 不同同时走,相同前停留;如果不同到,前进赋值好