Untitled
unknown
plain_text
2 years ago
2.5 kB
10
Indexable
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *next;
};
/* Given a reference (pointer to pointer) to the head
of a list and an int, appends a new node at the end */
void append(struct Node** head_ref, int new_data)
{
/* 1. allocate node */
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
struct Node *last = *head_ref;
int return_val = 0;
new_node->data = new_data;
new_node->next = NULL;
if (*head_ref == NULL)
{
*head_ref = new_node;
return_val = 1;
}
if (return_val != 1)
{
while (last->next != NULL)
last = last->next;
last->next = new_node;
}
return;
}
/*
Function to check if the 2 linked lists have the same data.
Return 1 if yes.
Return 0 if no.
*/
int compareList(struct Node* head_ref1, struct Node* head_ref2)
{
if (head_ref1 == NULL && head_ref2 == NULL)
return 1; // Both lists are empty, consider them identical
int result = 1;
while (head_ref1 != NULL && head_ref2 != NULL)
{
if (head_ref1->data != head_ref2->data)
{
result = 0;
break;
}
head_ref1 = head_ref1->next;
head_ref2 = head_ref2->next;
}
// If both lists are not empty or one list is not finished while the other is, they are not identical
if (head_ref1 != NULL || head_ref2 != NULL)
result = 0;
return result;
}
// This function prints contents of linked list starting from head
void printList(struct Node* node)
{
while (node != NULL)
{
printf("%d ", node->data);
node = node->next;
}
}
int main()
{
/* Start with the empty list */
struct Node* head1 = NULL;
struct Node* head2 = NULL;
/* Start code segment to read input: Do not touch */
int num_of_inputarray;
int i = 0;
int input_integer;
scanf("%d", &num_of_inputarray);
for (i = 0; i < num_of_inputarray; i++)
{
scanf("%d", &input_integer);
append(&head1, input_integer);
}
scanf("%d", &num_of_inputarray);
for (i = 0; i < num_of_inputarray; i++)
{
scanf("%d", &input_integer);
append(&head2, input_integer);
}
/* End code segment to read input: Do not touch */
printf("%d", compareList(head1, head2));
return 0;
}
Editor is loading...