第一种解题思路:看到题目空间复杂度为O(1),时间复杂度为O(n),意味着只能遍历链表一次,而且不能声明额外的辅助空间,因此直接从第二个节点开始判断,因为是递增的,所以只需要判断node和head的最后一个节点是否一致就行了,如果val一致,那么node就继续往后寻找,直到找到不同的val,然后放到head的尾部,继续遍历node,最后node为null记得将head的尾部置空,否则会出现尾部还会有重复的没有过滤,这样就能做到时间复杂度O(n),空间复杂度O(1)
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类
* @return ListNode类
*/
public ListNode deleteDuplicates (ListNode head) {
// write code here
if (head == null || head.next == null) {
return head;
}
ListNode node = head.next;
ListNode pre = head;
while (node != null) {
while (node != null && node.val == head.val) {
node = node.next;
}
if (node == null) {
//记得将head的尾部置空
head.next = null;
break;
}
head.next = node;
node = node.next;
head = head.next;
}
return pre;
}
}
第二种解题思路:只判断当前头节点是否和下一个头节点的val相同,相同就将next指向next的next,不相同就往下遍历,时间复杂度O(n),空间复杂度O(1)
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类
* @return ListNode类
*/
public ListNode deleteDuplicates (ListNode head) {
// write code here
if (head == null || head.next == null) {
return head;
}
ListNode pre = head;
while (head != null) {
if (head.next != null && head.val == head.next.val) {
head.next = head.next.next;
} else {
head = head.next;
}
}
return pre;
}
}