w3resource

C Exercises: Pair in a linked list whose sum is equal to a given value

C Singly Linked List : Exercise-38 with Solution

Write a C program to find a pair in a singly linked list whose sum is equal to a given value.

Sample Solution:

C Code:

#include<stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node* next;
};

// Function to create a new node
struct Node* newNode(int data) {
    struct Node* node = (struct Node*) malloc(sizeof(struct Node));
    node->data = data;
    node->next = NULL;
    return node;
}
void pairSum(struct Node *head, int sum) {
    struct Node *first = head;
    struct Node *second = NULL;
    int flag = 0;
    while (first != NULL && first->next != NULL) {
        second = first->next;

        while (second != NULL) {
            if ((first->data + second->data) == sum) {
                printf("(%d,%d) ", first->data, second->data);
                flag = 1;
            }
            second = second->next;
        }

        first = first->next;
    }
    if(flag==0)
     printf("Pair not found.\n");
}

// Function to print a linked list
void displayList(struct Node* head) {
    while (head) {
        printf("%d ", head->data);
        head = head->next;
    }
    printf("\n");
}

int main() {
    struct Node* head = newNode(1);
    head->next = newNode(2);
    head->next->next = newNode(3);
    head->next->next->next = newNode(4);
    head->next->next->next->next = newNode(5);
    head->next->next->next->next->next = newNode(6);
    head->next->next->next->next->next ->next = newNode(7);
    printf("Original singly linked list:\n");
    displayList(head);
    int s = 4;
    printf("\nFind a pair whose sum is equal to 4:\n");
    pairSum(head, s);
    s = 11;
    printf("\n\nFind a pair whose sum is equal to 11:\n");
    pairSum(head, s);
    s = 5;
    printf("\n\nFind a pair whose sum is equal to 5:\n");
    pairSum(head, s);
    s = 14;
    printf("\n\nFind a pair whose sum is equal to 14:\n");
    pairSum(head, s);

    return 0;
}

Sample Output:

Original singly linked list:
1 2 3 4 5 6 7 

Find a pair whose sum is equal to 4:
(1,3) 

Find a pair whose sum is equal to 11:
(4,7) (5,6) 

Find a pair whose sum is equal to 5:
(1,4) (2,3) 

Find a pair whose sum is equal to 14:
Pair not found.

Flowchart :

Flowchart: Pair in a linked list whose sum is equal to a given value.
Flowchart: Pair in a linked list whose sum is equal to a given value.

C Programming Code Editor:

Previous: Delete all elements greater than x from a linked list.
Next: Interleave elements of two linked lists alternatively.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.