Question:
Given a sorted list, and remove the duplicates in the list. For example, 1 -> 2 -> 2 -> 3, after removing the duplicates, we have 1 -> 2 -> 3
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (head == null || head.next == null) return head;
ListNode current = head.next;
ListNode previous = head;
previous.next = null;
while (current != null) {
if (current.val != previous.val) {
previous.next = current;
previous = current;
current = current.next;
previous.next = null;
} else {
current = current.next;
}
}
return head;
}
}
本文提供了一种从已排序链表中移除重复元素的方法。通过定义两个指针,分别用于标识当前节点和前一个节点,遍历链表并比较相邻节点值,当发现重复值时跳过当前节点,直至遍历完整个链表。
2120

被折叠的 条评论
为什么被折叠?



