admin管理员组文章数量:1596266
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
Analyze:
when we remove the duplicates, we consider all the duplicates as a composite node, and we remove the duplicates from the composite node and update the "next" value of the first node in the composite node.
Code:
public static Node removeDuplication(Node head) {
if (head == null || head.next == null ) return head;
Node listHead = head;
while (head != null) {
// if true, we will remove the nodes in the composite node
// and only keep the first node in the composite node
if (head.next != null && head.value == head.next.value) {
// the head of the composite node
Node headComposite = head;
while (head.next != null && head.value == head.next.value) {
head = head.next;
}
//head is the first node in the next composite node
head = head.next;
//update the next value
headComposite.next = head;
} else {
head = head.next;
}
}
return listHead;
}
转载请注明出处:http://blog.csdn/beiyeqingteng
本文标签: DuplicatesEliminateListsorted
版权声明:本文标题:eliminate the duplicates in the sorted list (2) 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/xitong/1728255855a1151004.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论