Skip to content

Instantly share code, notes, and snippets.

@wbadart
Created October 8, 2018 14:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wbadart/08813823beed6fb45664de8783706745 to your computer and use it in GitHub Desktop.
Save wbadart/08813823beed6fb45664de8783706745 to your computer and use it in GitHub Desktop.
Comparing two recursive ways to test linked list equivalence
#include "compare.h"
bool compare_lists(Node* a, Node* b) {
if(!a && !b)
return true;
else if((bool)a ^ (bool)b)
return false;
else
return a->data == b->data
&& compare_lists(a->next, b->next);
}
#pragma once
#include <stdbool.h>
#include "node.h"
bool compare_lists(Node* a, Node* b);
#include "compare.h"
bool _compare_lists(Node* a, Node* b, bool eq);
bool compare_lists(Node* a, Node* b) {
return _compare_lists(a, b, true);
}
bool _compare_lists(Node* a, Node* b, bool eq) {
if(!eq)
return false;
else if(!a && !b)
return true;
else if((bool)a ^ (bool)b)
return false;
else
return _compare_lists(
a->next, b->next,
eq && a->data == b->data);
}
#include <stdbool.h>
#include <stdio.h>
#include "compare.h"
#include "node.h"
int main(void) {
int n, m;
scanf("%d %d", &n, &m);
Node* a = read_list(n)
, * b = read_list(m);
bool eq = compare_lists(a, b);
printf("%d\n", eq);
return 0;
}
N=1000000
M=1000000
M2=1000001
compare: node.o compare.o main.o
$(CC) $^ -o $@
compare_tail: node.o compare_tail.o main.o
$(CC) $^ -o $@
%.o: %.c
$(CC) -c $< -o $@
input0:
echo "$(N) $(N)" > $@
shuf -i 1-$(N) > $@.tmp1
shuf -i 1-$(N) > $@.tmp2
cat $@.tmp1 >> $@
cat $@.tmp2 >> $@
rm $@.tmp{1,2}
input1:
echo "$(N) $(N)" > $@
shuf -i 1-$(N) > $@.tmp
cat $@.tmp >> $@
cat $@.tmp >> $@
rm $@.tmp
input2:
echo "$(N) $(M2)" > $@
shuf -i 1-$(N) > $@.tmp
cat $@.tmp >> $@
shuf -i 1-$(M2) > $@.tmp
cat $@.tmp >> $@
rm $@.tmp
benchmark: compare compare_tail input0 input1 input2
time ./compare < input0
time ./compare < input1
time ./compare < input2
time ./compare_tail < input0
time ./compare_tail < input1
time ./compare_tail < input2
.PHONY:
clean:
rm -f *.{o,s,out} input* compare compare_tail
#include <stdio.h>
#include <stdlib.h>
#include "node.h"
Node* read_list(int len) {
if(len <= 0)
return NULL;
Node* head = malloc(sizeof(Node))
, * curr = head;
for(int i = 0; i < len; i++) {
scanf("%d", &curr->data);
if(i < len - 1) {
curr->next = malloc(sizeof(Node));
curr = curr->next;
} else
curr->next = NULL;
}
return head;
}
#pragma once
typedef struct Node {
int data;
struct Node* next;
} Node;
Node* read_list(int len);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment