📌  相关文章
📜  在双向链表中查找具有给定和的四元组

📅  最后修改于: 2021-09-05 10:56:14             🧑  作者: Mango

给定一个已排序的双向链表和一个整数X ,任务是打印双向链表中总和为X 的所有四元组。

例子:

方法:给定的问题可以通过使用本文中讨论的思想使用 4 指针技术来解决。请按照以下步骤解决问题:

  • 初始化四个变量,说作为双向链表的开始即; first = head第二个到第一个指针的下一个,第三个到第二个指针的下一个,第四个到存储排序双向链表中所有 4 个元素的双向链表的最后一个节点。
  • 迭代一个循环,直到第一个节点和第四个节点不为NULL ,并且它们不相等并且这两个节点不相互交叉并执行以下步骤:
    • 第二个指针初始化为下一个 一个
    • 迭代一个循环,直到第二个第四个节点不为NULL ,它们不相等并且不相互交叉。
      • 初始化一个变量,比如sum as (X – (first→data + second→data)) ,将第三个指针指向第二个指针的下一个,并取另一个初始化为最后一个节点的临时指针,即指针第四个
      • 迭代一个循环,而tempthird不为NULL ,它们不相等并且不相互交叉
        • 如果总和的值是third→data + temp→data ,则打印四元组并将第三个指针增加到当前第三个指针的下一个,并将temp增加到当前 temp 的前一个。
        • 如果 sum的值小于第三个→data + temp→data ,则增加第三个指针,即第三个 = 第三个→next
        • 否则,递减临时指针,即temp = temp→prev
      • 第二个指针移动到下一个指针。
    • 将第一个指针移动到下一个指针。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Structure of node of a doubly
// linked list
struct Node {
    int data;
    struct Node *next, *prev;
};
 
// Function to insert a new node at
// the beginning of the doubly linked
// list
void insert(struct Node** head, int data)
{
    // Allocate the node
    struct Node* temp = new Node();
 
    // Fill in the data value
    temp->data = data;
    temp->next = temp->prev = NULL;
 
    if ((*head) == NULL)
        (*head) = temp;
    else {
        temp->next = *head;
        (*head)->prev = temp;
        (*head) = temp;
    }
}
 
// Function to print the quadruples
// having sum equal to x
void PrintFourSum(struct Node* head, int x)
{
    // First pointer to the head node
    struct Node* first = head;
 
    // Pointer to point to the second
    // node for the required sum
    struct Node* second;
 
    // Pointer to point to the third
    // node for the required sum
    struct Node* third;
 
    // Fourth points to the last node
    struct Node* fourth = head;
 
    // Update the fourth pointer to
    // the end of the DLL
    while (fourth->next != NULL) {
        fourth = fourth->next;
    }
 
    // Node to point to the fourth node
    // of the required sum
    struct Node* temp;
 
    while (first != NULL
           && fourth != NULL
           && first != fourth
           && fourth->next != first) {
 
        // Point the second node to the
        // second element of quadruple
        second = first->next;
 
        while (second != NULL
               && fourth != NULL
               && second != fourth
               && fourth->next != second) {
 
            int reqsum = x - (first->data
                              + second->data);
 
            // Points to the 3rd element
            // of quadruple
            third = second->next;
 
            // Points to the tail of the DLL
            temp = fourth;
 
            while (third != NULL && temp != NULL
                   && third != temp
                   && temp->next != third) {
 
                // Store the current sum
                int twosum = third->data
                             + temp->data;
 
                // If the sum is equal,
                // then print quadruple
                if (twosum == reqsum) {
 
                    cout << "(" << first->data
                         << ", "
                         << second->data
                         << ", "
                         << third->data
                         << ", "
                         << temp->data
                         << ")\n";
 
                    third = third->next;
                    temp = temp->prev;
                }
 
                // If twosum is less than
                // the reqsum then move the
                // third pointer to the next
                else if (twosum < reqsum) {
                    third = third->next;
                }
 
                // Otherwise move the fourth
                // pointer to the previous
                // of the fourth pointer
                else {
                    temp = temp->prev;
                }
            }
 
            // Move to the next of
            // the second pointer
            second = second->next;
        }
 
        // Move to the next of
        // the first pointer
        first = first->next;
    }
}
 
// Driver Code
int main()
{
    struct Node* head = NULL;
    insert(&head, 2);
    insert(&head, 1);
    insert(&head, 0);
    insert(&head, 0);
    insert(&head, -1);
    insert(&head, -2);
    int X = 0;
    PrintFourSum(head, X);
 
    return 0;
}


Python3
# Python3 program for the above approach
 
# Structure of node of a doubly
# linked list
class Node:
     
    def __init__(self, d):
         
        self.data = d
        self.left = None
        self.right = None
 
# Function to insert a new node at
# the beginning of the doubly linked
# list
def insert(head, data):
     
    # Allocate the node
    temp = Node(data)
 
    # Fill in the data value
    temp.data = data
    temp.next = temp.prev = None
 
    if (head == None):
        head = temp
    else:
        temp.next = head
        head.prev = temp
        head = temp
 
    return head
 
# Function to print the quadruples
# having sum equal to x
def PrintFourSum(head, x):
     
    # First pointer to the head node
    first = head
 
    # Pointer to point to the second
    # node for the required sum
    second = None
 
    # Pointer to point to the third
    # node for the required sum
    third = None
 
    # Fourth points to the last node
    fourth = head
 
    # Update the fourth pointer to
    # the end of the DLL
    while (fourth.next != None):
        fourth = fourth.next
 
    # Node to point to the fourth node
    # of the required sum
    temp = None
 
    while (first != None and
          fourth != None and
           first != fourth and
     fourth.next != first):
 
        # Point the second node to the
        # second element of quadruple
        second = first.next
 
        while (second != None and
               fourth != None and
               second != fourth and
          fourth.next != second):
 
            reqsum = x - (first.data +
                         second.data)
 
            # Points to the 3rd element
            # of quadruple
            third = second.next
 
            # Points to the tail of the DLL
            temp = fourth
 
            while (third != None and temp != None and
                   third != temp and temp.next != third):
 
                # Store the current sum
                twosum = third.data + temp.data
 
                # If the sum is equal,
                # then print quadruple
                if (twosum == reqsum):
 
                    print("(" + str(first.data) +
                         ", " + str(second.data) +
                         ", " + str(third.data) +
                         ", " + str(temp.data) + ")")
                    third = third.next
                    temp = temp.prev
 
                # If twosum is less than
                # the reqsum then move the
                # third pointer to the next
                elif (twosum < reqsum):
                    third = third.next
                     
                # Otherwise move the fourth
                # pointer to the previous
                # of the fourth pointer
                else:
                    temp = temp.prev
 
            # Move to the next of
            # the second pointer
            second = second.next
 
        # Move to the next of
        # the first pointer
        first = first.next
 
# Driver Code
if __name__ == '__main__':
     
    head = None
    head = insert(head, 2)
    head = insert(head, 1)
    head = insert(head, 0)
    head = insert(head, 0)
    head = insert(head, -1)
    head = insert(head, -2)
    X = 0
     
    PrintFourSum(head, X)
     
# This code is contributed by mohit kumar 29


输出:
(-2, -1, 1, 2)
(-2, 0, 0, 2)
(-1, 0, 0, 1)

时间复杂度: O(N 3 )
辅助空间: O(1)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live