DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Floyd's Cycle Algorithm for Fraud Detection in Java Systems
  • Process Mining Key Elements
  • Avoiding Pitfalls With Java Optional: Common Mistakes and How To Fix Them [Video]
  • Sliding Window

Trending

  • Beyond ChatGPT, AI Reasoning 2.0: Engineering AI Models With Human-Like Reasoning
  • Unlocking the Potential of Apache Iceberg: A Comprehensive Analysis
  • Create Your Own AI-Powered Virtual Tutor: An Easy Tutorial
  • How the Go Runtime Preempts Goroutines for Efficient Concurrency
  1. DZone
  2. Data Engineering
  3. AI/ML
  4. Linked List Popular Problems Vol. 1

Linked List Popular Problems Vol. 1

This article will show how to solve three popular linked list problems: Linked List Cycle, Middle of the Linked List, and Remove Duplicates from Sorted List.

By 
Sergei Golitsyn user avatar
Sergei Golitsyn
·
Nov. 17, 22 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
10.8K Views

Join the DZone community and get the full member experience.

Join For Free

Aloha guys. Today we are trying to solve three popular linked list problems: Linked List Cycle, Middle of the Linked List, and Remove Duplicates from Sorted List.

Let's start with my favorite Leetcode problem. 

Linked List Cycle

Description

Given head, the head of a linked list determines if the linked list has a cycle in it.

There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos denotes the index of the node that the tail's next pointer is connected to. Note that pos is not passed as a parameter.

Return true if there is a cycle in the linked list. Otherwise, return false.

 Example 1:

 
Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).


Example 2:

 
Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 0th node.


Example 3:

 
Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.


Solution

Let's imagine a running circle.  And then, we add two runners to this circle. 

If one of the runners is faster, it is obvious that the fastest runner will catch up with the slowest.

I'm going to use the same principle in my algorithm. I want to prepare two runners; slow and fast. After it, we should iterate till the end. Do you understand what it means 'end' in our case? We have two endings: the list has a cycle, and pointers will meet, and we have a null at the end of the list. 

Let's implement it:

Java
 
    public boolean hasCycle(ListNode head) {
        if(head == null || head.next == null){
            return false;
        }

        ListNode fast = head.next;
        while(head != fast){
            if (fast.next == null || fast.next.next == null){
                return false;
            } else {
                head = head.next;
                fast = fast.next.next;
            }
        }
        return true;
    }


Our next today's problem is...

Middle of the Linked List

Description

Given the head of a singly linked list, return the middle node of the linked list.

If there are two middle nodes, return the second middle node.

 Example 1:

Middle of the linked list.

 
Input: head = [1,2,3,4,5]
Output: [3,4,5]
Explanation: The middle node of the list is node 3.


Example 2:

Middle of the linked list.

 
Input: head = [1,2,3,4,5,6]
Output: [4,5,6]
Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one.


Solution

This problem can be tricky, but I will explain a few algorithms to solve it.

For example, we can iterate over the list and calculate the size of the list, and then iterate to the middle element =) Super simple. 

In the second variant, we can use the same approach as in the previous problem; two pointers. 

We are preparing slow and fast pointers and iterating till the end of the list. And that is it. When our fast pointer will be in the end, the slow one will be in the list middle.

Sure, don't forget about the borders. It is extremely important to check fast pointer is not null and fast.next, not null.


Java
 
    public ListNode middleNode(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        
        while(fast != null && fast.next != null){
            slow = slow.next;
            fast = fast.next.next;
        }
        
        return slow;
    }


Remove Duplicates From the Sorted List

Description

Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.

 Example 1:

Removal of Duplicates.

 
Input: head = [1,1,2]
Output: [1,2]


Example 2:

Remove Duplicates From Sorted List

 
Input: head = [1,1,2,3,3]
Output: [1,2,3]


Solution

The main trick in this problem is to understand how we can eliminate duplicate elements. Also, we should check the borders. In this algorithm, we will check the current element and the next one. If elements are the same, we should set cur.next to cur.next.next. Is it clear? you can ask me in the comments.


Java
 
    public ListNode deleteDuplicates(ListNode head) {
        ListNode rez = head;
        while(head != null && head.next != null){
            if(head.val == head.next.val){
                head.next = head.next.next;
            } else {
                head = head.next;
            }
        }
        return rez;
    }


Fastest HTTPS Algorithm Clear (Unix) Element Java (programming language) Pointer (computer programming)

Opinions expressed by DZone contributors are their own.

Related

  • Floyd's Cycle Algorithm for Fraud Detection in Java Systems
  • Process Mining Key Elements
  • Avoiding Pitfalls With Java Optional: Common Mistakes and How To Fix Them [Video]
  • Sliding Window

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!