题解 | 删除有序链表中重复的元素-I
删除有序链表中重复的元素-I
https://www.nowcoder.com/practice/c087914fae584da886a0091e877f2c79
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @return ListNode类
*/
public ListNode deleteDuplicates (ListNode head) {
if (head == null || head.next == null) {
return head;
}
//当前元素
ListNode current = head;
//上一个元素
ListNode preNode = null;
while (current != null) {
if (preNode != null) {
//如果值不相等
if (current.val != preNode.val) {
//把上一个值指向当前值
preNode.next = current;
//记录当前的值方便下次使用
preNode = current;
} else {
//相等需要断开连接,没有这一个所有都相同的通不过
preNode.next = null;
}
} else {
preNode = current;
}
current = current.next;
}
return head;
}
}
查看9道真题和解析