题解 | #删除有序链表中重复的元素-I#
删除有序链表中重复的元素-I
https://www.nowcoder.com/practice/c087914fae584da886a0091e877f2c79
思路
由于链表是有序的,所以,重复元素必定相邻。 遍历链表,使用一个变量记录当前元素,当遍历到下一个位置时,对比一下是否相同。 如果相同,则删除,反之继续将当前数值赋值给该变量
代码
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类
* @return ListNode类
*/
public ListNode deleteDuplicates (ListNode head) {
// 代码健壮性检验
if (head == null || head.next == null) {
return head;
}
// 创建一个变量,用于存放当前节点数据
int temp = head.val;
ListNode curr = head.next;
ListNode pre = head;
while (true) {
// 如果上一节点值等于当前节点,删除当前节点
if (curr.val == temp) {
pre.next = curr.next;
curr = curr.next;
} else if (curr.val != temp) {
temp = curr.val;
pre = pre.next;
curr = curr.next;
}
if (curr == null) {
break;
}
}
return head;
}
}