在做leetcode力扣时候, 遇到一个问题是消除有序list中的重复值,比如head = [1,1,2]则返回[1,2], 如果是head = [1,1,2,3,3]则返回[1,2,3]. 正确的代码如下:
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode list = head;
while(list != null) {
if (list.next == null) {
break;
}
if (list.val == list.next.val) {
list.next = list.next.next;
} else {
list = list.next;
}
}
return head;
}
}
我的问题是,为什么不能直接采用参数head? ,而是需要新建一个ListNode List来等于head?不是很理解这里,我试了下如果直接用参数head进行代码则结果是错误的,输入[1,1,2]会返回[2] ,比如:
错误代码:
class Solution {
public ListNode deleteDuplicates(ListNode head) {
while(head != null){
if(head.next == null){
break;
}
if (head.val == head.next.val){
head.next= head.next.next;
}else{
head = head.next;
}
}
return head;
}
}