83. 删除排序链表中的重复元素
迭代
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode dummyHead = new ListNode(-1);
dummyHead.next = head;
ListNode cur = head;
ListNode next;
while (cur != null){
next = cur.next;
/**
* 如果cur是最后一个节点,就结束循环了
*/
if (next != null && cur.val == next.val){
cur.next = next.next;
}
else {
cur = cur.next;
}
}
return dummyHead.next;
}
}
/**
* 时间复杂度 O(n)
* 空间复杂度 O(1)
*/
递归
public class Algorithm {
public static void main(String[] args) {
int[] arr = {1, 2, 4, 4, 7, 8, 9, 9};
ListNode head = new ListNode(arr);
System.out.println(head);
System.out.println(new Solution().deleteDuplicates(head));
}
}
class Solution {
public ListNode deleteDuplicates(ListNode head) {
/**
* 递归终止条件:遇到的节点为空
*/
if (head == null){
return head;
}
ListNode son = deleteDuplicates(head.next);
/**
* 如果子链表不为空,将子链表头节点和head进行对比,相同则返回son,否则将head加到链表首端
*/
if(son != null && head.val == son.val){
return son;
}
else {
head.next = son;
return head;
}
}
}
class ListNode{
int val;
ListNode next;
ListNode() {}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val; this.next = next;
}
ListNode(int[] arr){
if (arr == null || arr.length == 0){
throw new IllegalArgumentException("数组是空的");
}
this.val = arr[0];
ListNode prev = this;
for (int i = 1; i < arr.length; i++) {
prev.next = new ListNode(arr[i]);
prev = prev.next;
}
}
@Override
public String toString(){
StringBuilder str = new StringBuilder();
ListNode curr = this;
while (curr != null){
str.append(curr.val + "——>");
curr = curr.next;
}
str.append("null");
return str.toString();
}
}
/**
* 时间复杂度 O(n)
* 空间复杂度 O(logn)
*/
https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/