- 思路
要考虑到有可能重复的元素有很多个,因此下面代码不正确
/**
* Definition for ListNode
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
/**
* @param ListNode head is the head of the linked list
* @return: ListNode head of linked list
*/
public static ListNode deleteDuplicates(ListNode head) {
// write your code here
if(head==null){
return null;
}
if(head.next==null){
return head;
}
ListNode p = head;
while(p.next!=null){
if(p.next.val==p.val){
p.next=p.next.next;
}
p=p.next;
}
return head;
}
}
这样的话,无论怎样都只是比较一次,然后p就往后移动了。如果出现这样情况比如13-13-13-13-13-13-14-15
13-13-13-13-14。。。只会删除中间的
/**
* Definition for ListNode
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
/**
* @param ListNode head is the head of the linked list
* @return: ListNode head of linked list
*/
public static ListNode deleteDuplicates(ListNode head) {
// write your code here
if(head==null){
return null;
}
if(head.next==null){
return head;
}
ListNode p = head;
while(p.next!=null){
if(p.next.val==p.val){
p.next=p.next.next;
}else{
p=p.next;
}
}
return head;
}
}
正确的做法就是一直比较,一直比。直到最开始的那个元素后面都没有重复的了才可以