struct node {
int data;
struct node *next;
struct node *prev;
};
struct node *start = NULL; // pointer to start of list.
struct node *end = NULL; // pointer to end of list
struct node * create (data)
int data;
{
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->data = data;
temp->next = temp->prev = NULL;
return temp;
}
struct node * push(start, temp)
struct node *start;
struct node *temp;
{
if(start == NULL) {
// this node is the first node, assign it as is.
start = temp;
} else {
temp->next = start;
start->prev = temp;
start = temp;
}
return start;
}
####
package doublyLinkedList;
sub new {
my ($class, @elements) = @_;
my $self = bless {
start => undef,
}, $class;
$self->push(@elements);
return $self;
}
sub push {
my ($self, @elements) = @_;
for my $element (@elements) {
my $newNode = {
element => $element,
next => undef,
prev => undef,
}; # newNode becomes an anonymous hash ref.
if(not defined $self->{start}) {
$self->{start} = $newNode; # the list is empty, assign to start as is
} else {
$newNode->{next} = $self->{start};
$self->{start}{prev} = $newNode;
$self->{start} = $newNode; # else make the new node point to start and then assign new node as the new start of the list.
}
}
return;
}
####
void pop(start)
struct node *start;
{
if(start == NULL) {
printf("The list is empty!\n");
return;
}
struct node *temp = start;
start = temp->next;
temp->next = start->prev = NULL;
free(temp);
return; # or maybe we can return the element popped before freeing temp or whatever.
}
####
sub pop {
my $self = shift;
my $ret = $self->{start};
return if not defined $ret; # return if the list is empty.
$self->{start} = $ret->{next};
$self->{start}{prev} = $ret->{next} = undef;
return $ret->{element};
}