Remove duplicates from a sorted linked list


Introduction

Before reading this article, It is recommended to have an understanding of the linked list and its implementation and some basic operations on the linked list.


Remove duplicates from a sorted linked list

Problem Description

Create a function that takes a non-descending list and removes any duplicate nodes. Only one traversal of the list is necessary. Eg. Consider the given linked list: 1->1->1->2->2->3, the function is expected to convert the linked list into 1->2->3.

In this article, we will extensively discuss the Label Control in C# & how to remove duplicates from sorted doubly linked list

Important: We are supposed to delete only the duplicates i.e. only one copy of nodes should be there.

Intuition: The biggest hint given is that the list is sorted or non-decreasing in nature. From this, we can deduce that if duplicates are present, then it has to be the next one in the chain.

The ideal way to approach this problem is to simply loop through the first value in a duplicate set until you locate a non-duplicate value or reach the end of the list. Adjust the next value of the node to point to the location after the "inner" loop when you obtain a non-duplicate or reach the end.

First, we'll see if the List is empty. Curr should be set to head, and next to curr.next. We'll loop until the next is null; if curr is the only node in the list, the loop will be skipped. Use a while loop to fetch the node after next once you've found a duplicate.

If a non-duplicate is detected, exit the loop; else, the next will reach the end and be null. Set next to curr.next and curr.next to next, then curr = curr.next;. Finally, because no modifications were made to that reference, nodes after it was changed, return head.

/**

  • struct ListNode {
  • int val;
  • ListNode *next;
  • ListNode() : val(0), next(nullptr) {}
  • ListNode(int x) : val(x), next(nullptr) {}
  • ListNode(int x, ListNode *next) : val(x), next(next) {}
  • }; */

See the entire article...




Comments

Popular posts from this blog

What are the 5 types of inheritance?

How often can you Buy and Sell the same stock?