Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5
, return 1->2->5
.
Given 1->1->1->2->3
, return 2->3
.
There are two ways to solve this problem. One is recursive, the subproblem is that if the head node has duplicates, we find the next node different from the head node and continue. If the head node doesn't have duplicates, then we continue to deal with the node next to the head node. The other one is iterative. We can create a temporary node and makes it point to the head node. Each time if the node has duplicates, we delete them.
C++ Code:
/* * func: remove_duplicates * goal: delete all nodes that have duplicates * @param head: head node of the list * return: head node of the list */ ListNode *remove_duplicates(ListNode *head){ if(head == nullptr || head->next == nullptr){ return head; } //Set up a new node and connect it to the head node ListNode *tmp_head = new ListNode(numeric_limits<int>::max()); tmp_head->next = head; ListNode *iter = tmp_head; while(iter->next){ ListNode *next_node = iter->next; while(next_node != nullptr && next_node->val == next_node->next->val){ next_node = next_node->next; } if(next_node != iter->next){ iter->next = next_node->next; }else{ iter = iter->next; } } return tmp_head->next; }
Python Code:
# func: remove all elements if it has duplicates # @param head: head node of the list # @return: new head def remove_duplicates(head): if not head or not head.next: return head iter = head.next if head.val == iter.val: while head.val == iter.val: iter = iter.next if not iter: break return remove_duplicates(iter) else: head.next = remove_duplicates(head.next) return head
No comments:
Post a Comment