eliminate the duplicates in a sorted linked list (1)
来源:互联网 发布:软件开发书籍推荐 编辑:程序博客网 时间:2024/06/06 19:09
Qustion:
Given a sorted linked list, and remove all the nodes which have duplication. For example, 1 -> 1 -> 2 -> 2 -> 3 ->4 , after removing duplicates, the linked list becomes 3 ->4.
Analyze:
1. In order to remove the duplicated nodes in the list, we consider the duplicates as a composite node. After removing the composite node, we need to make sure that remaining nodes are still connected. Therefore, we need to have a pointer which points to the parent node of the composite node. When the composite node is removed, the parent node will point to the next non-duplicated node.
2. If the first node belongs to a composite node, we need to return a new head.
Code:
public static Node removeDuplication(Node head) {if (head == null || head.next == null ) return head;//father nodeNode prev = null;Node newHead = null;//if the newhead has been determined,//we will not change the head any more.boolean headunchanged = true;while (head != null) {// if true, we will remove the composite nodeif (head.next != null && head.value == head.next.value) {while (head.next != null && head.value == head.next.value) {head = head.next;}head = head.next;if (head == null && prev != null) {prev.next = null;}} else {//change head if applicableif (headunchanged == true) {newHead = head;headunchanged = false;}//update the next value in the prev nodeif (prev != null) {prev.next = head;}prev = head;head = head.next;}}return newHead;}http://blog.csdn.net/beiyeqingteng
- eliminate the duplicates in a sorted linked list (1)
- eliminate the duplicates in a sorted linked list (1)
- eliminate the duplicates in the sorted list (2)
- eliminate the duplicates in the sorted list (2)
- Insert a node in a sorted linked list.
- Remove duplicate in sorted linked list 1
- merge two sorted linked list with duplicates
- merge two sorted linked list without duplicates
- merge two sorted linked list with duplicates
- LeetCode[Linked List]: Remove Duplicates from Sorted List II
- 83. Remove Duplicates from Sorted List(Linked List)
- 83. Remove Duplicates from Sorted List(Linked List-Easy)
- 1007. Find the middle element in a Linked List
- Convert a BST to a sorted doubly-linked list in-place
- Remove duplicates in a sorted array
- Insert in a sorted list
- eliminate duplicates
- Remove Duplicates from Sorted List && Merge Two Sorted Lists && Linked List Cycle && Remove Nth Node
- 安装MYSLQ数据库异常cannot create windows service for mysql.error:0
- eliminate the duplicates in the sorted list (2)
- ssh 启动服务时加载数据
- 中兴ZTE制造,某款Firefox OS原型机曝光。
- vc++建立web中ActiveX插件的过程
- eliminate the duplicates in a sorted linked list (1)
- Manifolds with singularities
- SAP HANA 评估测试(SAP HANA Exam Test)
- Android中集成第三方软件包(.jar, .so)
- 使用nginx后如何在web应用中获取用户ip及原理解释
- merge two sorted linked list with duplicates
- 课程设计
- Android 关于android:name属性问题
- add two linked list as integer