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

📅  最后修改于: 2022-05-13 01:57:44.713000             🧑  作者: Mango

在双向链表中查找具有给定总和的对

给定一个正不同元素的排序双向链表,任务是在双向链表中找到总和等于给定值 x 的对,而不使用任何额外的空间?

例子:

Input : head : 1 <-> 2 <-> 4 <-> 5 <-> 6 <-> 8 <-> 9
        x = 7
Output: (6, 1), (5,2)

预期的时间复杂度为 O(n),辅助空间为 O(1)。

这个问题的一个简单的方法是一个一个地选择每个节点,并通过向前遍历在剩余的列表中找到一个其总和等于 x 的第二个元素。此问题的时间复杂度为 O(n^2),n 是双向链表中的节点总数。

此问题的有效解决方案与本文相同。这是算法:



  • 初始化两个指针变量以在已排序的双向链表中查找候选元素。首先用双向链表的开头进行初始化,即; first=head并用双向链表的最后一个节点初始化second ,即;第二=最后一个节点
  • 我们将第一个第二个指针初始化为第一个和最后一个节点。这里我们没有随机访问,所以为了找到第二个指针,我们遍历列表来初始化第二个。
  • 如果firstsecond 的当前总和小于 x,那么我们首先向前移动。如果第一个第二个元素的当前总和大于 x,那么我们向后移动第二个
  • 循环终止条件也不同于数组。当两个指针相互交叉(second->next = first),或者它们变得相同(first == second)时,循环终止。
  • 不存在对的情况将由条件“first==second”处理
C++
// C++ program to find a pair with given sum x.
#include
using namespace std;
 
// structure of node of doubly linked list
struct Node
{
    int data;
    struct Node *next, *prev;
};
 
// Function to find pair whose sum equal to given value x.
void pairSum(struct Node *head, int x)
{
    // Set two pointers, first to the beginning of DLL
    // and second to the end of DLL.
    struct Node *first = head;
    struct Node *second = head;
    while (second->next != NULL)
        second = second->next;
 
    // To track if we find a pair or not
    bool found = false;
 
    // The loop terminates when two pointers
    // cross each other (second->next
    // == first), or they become same (first == second)
    while (first != second && second->next != first)
    {
        // pair found
        if ((first->data + second->data) == x)
        {
            found = true;
            cout << "(" << first->data<< ", "
                << second->data << ")" << endl;
 
            // move first in forward direction
            first = first->next;
 
            // move second in backward direction
            second = second->prev;
        }
        else
        {
            if ((first->data + second->data) < x)
                first = first->next;
            else
                second = second->prev;
        }
    }
 
    // if pair is not present
    if (found == false)
        cout << "No pair found";
}
 
// A utility function to insert a new node at the
// beginning of doubly linked list
void insert(struct Node **head, int data)
{
    struct Node *temp = new Node;
    temp->data = data;
    temp->next = temp->prev = NULL;
    if (!(*head))
        (*head) = temp;
    else
    {
        temp->next = *head;
        (*head)->prev = temp;
        (*head) = temp;
    }
}
 
// Driver program
int main()
{
    struct Node *head = NULL;
    insert(&head, 9);
    insert(&head, 8);
    insert(&head, 6);
    insert(&head, 5);
    insert(&head, 4);
    insert(&head, 2);
    insert(&head, 1);
    int x = 7;
 
    pairSum(head, x);
 
    return 0;
}


Java
// Java program to find a
// pair with given sum x.
class GFG
{
 
// structure of node of
// doubly linked list
static class Node
{
    int data;
    Node next, prev;
};
 
// Function to find pair whose
// sum equal to given value x.
static void pairSum( Node head, int x)
{
    // Set two pointers, first
    // to the beginning of DLL
    // and second to the end of DLL.
    Node first = head;
    Node second = head;
    while (second.next != null)
        second = second.next;
 
    // To track if we find a pair or not
    boolean found = false;
 
    // The loop terminates when 
    // they cross each other (second.next
    // == first), or they become same
    // (first == second)
    while ( first != second && second.next != first)
    {
        // pair found
        if ((first.data + second.data) == x)
        {
            found = true;
            System.out.println( "(" + first.data +
                                ", "+ second.data + ")" );
 
            // move first in forward direction
            first = first.next;
 
            // move second in backward direction
            second = second.prev;
        }
        else
        {
            if ((first.data + second.data) < x)
                first = first.next;
            else
                second = second.prev;
        }
    }
 
    // if pair is not present
    if (found == false)
        System.out.println("No pair found");
}
 
// A utility function to insert
// a new node at the beginning
// of doubly linked list
static Node insert(Node head, int data)
{
    Node temp = new Node();
    temp.data = data;
    temp.next = temp.prev = null;
    if (head == null)
        (head) = temp;
    else
    {
        temp.next = head;
        (head).prev = temp;
        (head) = temp;
    }
    return temp;
}
 
// Driver Code
public static void main(String args[])
{
    Node head = null;
    head = insert(head, 9);
    head = insert(head, 8);
    head = insert(head, 6);
    head = insert(head, 5);
    head = insert(head, 4);
    head = insert(head, 2);
    head = insert(head, 1);
    int x = 7;
 
    pairSum(head, x);
}
}
 
// This code is contributed
// by Arnab Kundu


Python3
# Python3 program to find a pair with
# given sum x.
 
# Structure of node of doubly linked list
class Node:
     
    def __init__(self, x):
         
        self.data = x
        self.next = None
        self.prev = None
 
# Function to find pair whose sum
# equal to given value x.
def pairSum(head, x):
     
    # Set two pointers, first to the
    # beginning of DLL and second to
    # the end of DLL.
    first = head
    second = head
     
    while (second.next != None):
        second = second.next
 
    # To track if we find a pair or not
    found = False
 
    # The loop terminates when they
    # cross each other (second.next ==
    # first), or they become same
    # (first == second)
    while (first != second and second.next != first):
             
        # Pair found
        if ((first.data + second.data) == x):
            found = True
            print("(", first.data, ",",
                       second.data, ")")
             
            # Move first in forward direction
            first = first.next
             
            # Move second in backward direction
            second = second.prev
        else:
            if ((first.data + second.data) < x):
                first = first.next
            else:
                second = second.prev
 
    # If pair is not present
    if (found == False):
        print("No pair found")
 
# A utility function to insert a new node
# at the beginning of doubly linked list
def insert(head, data):
     
    temp = Node(data)
     
    if not head:
        head = temp
    else:
        temp.next = head
        head.prev = temp
        head = temp
         
    return head
 
# Driver code
if __name__ == '__main__':
     
    head = None
    head = insert(head, 9)
    head = insert(head, 8)
    head = insert(head, 6)
    head = insert(head, 5)
    head = insert(head, 4)
    head = insert(head, 2)
    head = insert(head, 1)
    x = 7
 
    pairSum(head, x)
 
# This code is contributed by mohit kumar 29


C#
// C# program to find a
// pair with given sum x.
using System;
 
class GFG
{
 
    // structure of node of
    // doubly linked list
    class Node
    {
        public int data;
        public Node next, prev;
    };
 
    // Function to find pair whose
    // sum equal to given value x.
    static void pairSum( Node head, int x)
    {
        // Set two pointers, first
        // to the beginning of DLL
        // and second to the end of DLL.
        Node first = head;
        Node second = head;
        while (second.next != null)
            second = second.next;
 
        // To track if we find a pair or not
        bool found = false;
 
        // The loop terminates when 
        // they cross each other (second.next
        // == first), or they become same
        // (first == second)
        while (first != second && second.next != first)
        {
            // pair found
            if ((first.data + second.data) == x)
            {
                found = true;
                Console.WriteLine( "(" + first.data +
                                    ", "+ second.data + ")" );
 
                // move first in forward direction
                first = first.next;
 
                // move second in backward direction
                second = second.prev;
            }
            else
            {
                if ((first.data + second.data) < x)
                    first = first.next;
                else
                    second = second.prev;
            }
        }
 
        // if pair is not present
        if (found == false)
            Console.WriteLine("No pair found");
    }
 
    // A utility function to insert
    // a new node at the beginning
    // of doubly linked list
    static Node insert(Node head, int data)
    {
        Node temp = new Node();
        temp.data = data;
        temp.next = temp.prev = null;
        if (head == null)
            (head) = temp;
        else
        {
            temp.next = head;
            (head).prev = temp;
            (head) = temp;
        }
        return temp;
    }
 
    // Driver Code
    public static void Main(String []args)
    {
        Node head = null;
        head = insert(head, 9);
        head = insert(head, 8);
        head = insert(head, 6);
        head = insert(head, 5);
        head = insert(head, 4);
        head = insert(head, 2);
        head = insert(head, 1);
        int x = 7;
 
        pairSum(head, x);
    }
}
 
// This code is contributed by 29AjayKumar


Javascript


输出:

(1,6) 
(2,5)

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

如果链表没有排序,那么我们可以将列表排序作为第一步。但在那种情况下,整体时间复杂度将变为 O(n Log n)。如果额外空间不是约束,我们可以在这种情况下使用哈希。基于散列的解决方案与此处的方法 2 相同。

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程