[Data Structure]-Linked List Problem Solved by Fast and Slow Pointers

Speaking of the singly linked list in the data structure, we can think of a lot of questions about this structure. This article mainly summarizes several problems about solving with the same method-fast and slow pointers~
1. The first question-return to the middle node of the linked list
Topic requirements:

Thinking solution:

& Using the fast and slow pointers, the fast pointer takes two steps at a time, and the slow pointer takes one step at a time
& finally return the slow pointer
& Note that when looping, fast != NULL && fast->next != NULL, because there are cases where the number of nodes is odd or even

Code:

ListNode* middleNode(ListNode* head) {
       ListNode* fast = head;
       ListNode* slow = head;
       while(fast != NULL && fast->next != NULL)
       {
           fast = fast->next->next;
           slow = slow->next;
       }
       return slow;
}

Second, the second question-returns the penultimate k-th node in the linked list
Enter a linked list and output the penultimate k-th node in the linked list

Problem-solving ideas:
& The idea of ​​the previous question is still the same, using fast and slow pointers to solve
& Special considerations: when the node is empty or k<0, it should return empty
& First let the fast pointer go k-1 first
& then go synchronously
& finally return the full correction value

Code:

ListNode*
FindKthToTail(ListNode* pListHead, unsigned int k) {
        if(pListHead == 0 || k<=0)
            return NULL;
        ListNode* fast = pListHead;
        ListNode* slow = pListHead;
        for(int i = 0;i<k-1;i++)
        {
            if(fast->next != NULL)
            {
               fast = fast->next;
            }
            else  return NULL;     
        }
        while(fast -> next != NULL)
        {
           fast = fast ->next;
           slow = slow->next;
        }
        return slow;
}

Third, the third question-judge whether it is a palindrome structure

Thinking solution:
& Using the fast and slow pointers, the first step is to set a fast pointer and a slow pointer
& The fast pointer takes two steps at a time, and the slow pointer takes one step at a time. When the next step of the fast pointer is null, it means that the slow pointer has gone halfway, so that you can find the intermediate node
& then reverse the pointer behind the middle linked list
& Scan from beginning to end to the middle, compare whether each element is equal, if they are equal, it is the number of palindromes, otherwise it is not the number of palindromes

Code:

bool
chkPalindrome(ListNode* A) {
        if(A == NULL)
        return false;
    else if(A->next == NULL)
        return true;
    //Fast and slow pointer to find the middle node
    ListNode* fast = A;
    ListNode* slow = A;
    while(fast != NULL && fast->next!= NULL)
    {
        fast = fast->next->next;
        slow = slow->next;
    }
         //Reverse
    ListNode* p = slow->next;
    ListNode* p1 = p->next;
    while(p != NULL)
    {
        p->next = slow;
        slow = p;
        p = p1;
        p1 = p1->next;
    }
         //Compare
    while(A != slow)
    {
        if((A->val) != (slow->val))
        {
           return false;
        }
        else 
        {
           if(A->next == slow)
           {
              return true;
           }
           A = A->next;
           slow = slow->next;
        }
    }
    return true;
}

Fourth, the fourth question-determine whether there is a ring in the linked list


Thinking solution:
& Using fast and slow pointers, imagine two athletes, if they meet, it means there is a ring

Code:

bool hasCycle(ListNode *head) {
    if(head == NULL)
        return NULL;
    ListNode* fast = head;
    ListNode* slow = head;
    while(fast != NULL && fast->next != NULL)
    {
        fast = fast->next->next;
        slow = slow->next;
        if(fast == slow)
            return true;
    }
    return false;
}

V. Question 5-Return to the first node of the linked list

Thinking solution:
& Note! In the previous question, in our solution, the meeting point of the ring is not necessarily the starting point of the ring
& According to the law, we can use mathematical formulas to derive, the length of the non-ring part + the length of the ring starting point to the meeting point is an integer multiple of the ring. This means that the two pointers have just walked a lot of circles from the meeting point and then traveled x distance, which means that if they walked from the meeting point and then traveled x, they will reach the starting point of the ring.
& How can I take step x? ——Let one pointer start from the beginning, the other pointer starts from the meeting point, and when the two pointers meet, it will take x steps, this is the starting point of the ring

Code:

ListNode *detectCycle(ListNode *head) {
        ListNode* fast = head;
    ListNode* slow = head;
    while(fast != NULL && fast->next != NULL)
    {
        fast = fast->next->next;
        slow = slow->next;
        if(fast == slow)
        {
            fast = head;
            while(fast != slow)
            {
                fast = fast->next;
                slow = slow->next;
            }
            return fast;
        }
    }
    return NULL;
}

Intelligent Recommendation

LeetCode-Summary of linked list fast and slow pointers

Linked list speed pointer       The speed of the pointer refers to the step length of the pointer moving along the linked list, that is, the speed of the forward movement each time. The...

Use fast and slow pointers to access the data of the middle node of the (bidirectional) linked list (bidirectional linked list with head node)

This article mainly introduces the method of using fast and slow pointers to access intermediate nodes. As for other operations of the linked list, it has been written before, and I wo n’t intro...

[Leetcode/linked list] circular linked list (application of fast and slow pointers)

Problem Description: Given a linked list, determine whether there is a ring in the linked list. To represent the rings in a given linked list, we use integerspos To indicate the position where the end...

Data structure exercise 1-fast and slow pointers

The speed in the speed pointer refers to the step length of the movement, that is, the speed of each forward movement. For example, you can make the fast pointer move forward 2 times along the linked ...

Use the principle of fast and slow pointers to get the data of the middle node of the singly linked list

The common method is to traverse once to get the table length, and then move to the middle according to this value The fast and slow pointer method can improve efficiency. When the fast pointer reache...

More Recommendation

Fast and slow pointers to find the middle value of a single linked list

The program is valid, the idea of ​​the speed and slow pointer can be seen at https://www.bilibili.com/video/av29175690/?p=16...

141. Circular linked list (fast and slow pointers and hash tables)

Title: Given a linked list, determine whether there is a ring in the linked list Links:https://leetcode-cn.com/problems/linked-list-cycle/ Idea 1 fast and slow pointer : Imagine that the rabbit and th...

Use fast and slow pointers to determine the rings in the linked list

Still compare the linked list to a runway, there are loops in the linked list, then this runway is a circular runway, in a circular runway, if two people have a speed difference, then two people will ...

LeetCode circular linked list (Python)-fast and slow pointers

topic Problem solving ideas The straightforward idea is to store the traversed nodes in a list, and then see if the currently traversed node has been traversed before: The result is really closed: Ano...

The Kth node from the bottom of the linked list of fast and slow pointers

Title description Implement an algorithm to find the kth node from the bottom in the singly linked list. Returns the value of this node. Example: Problem solving ideas Fast and slow pointer is a class...

Copyright  DMCA © 2018-2026 - All Rights Reserved - www.programmersought.com  User Notice

Top