The awkwardness of having to keep a “previous” pointer while operating on a list using a
loop can be avoided by maintaining these pointers in the data structure itself.
struct node {
int first;
struct node *rest;
struct node *prev;
}
Write the following C functions.
struct node *cons(int v, struct node *lst)
Adds the value v to the front of the list and returns a pointer to the resulting list.
void add_after(int v, struct node *nptr)
Adds the value v after the node pointed to by nptr (which cannot be NULL).
struct node *remove_first(struct node *lst, int key)
Removes the first occurrence of key in the list pointed to by lst (assumed to point to the
first element), or has no effect if that value does not appear in the list, and returns a pointer
to the resulting list.
To submit: doubly.c, doubly-driver.c.
Alright so far I'm having trouble with the cons function so far I have
Code:
#include <stdlib.h>
#include <stdio.h>
#include "doubly.h"
struct node *cons(int v, struct node *lst)
{
struct node *new = malloc(sizeof(struct node));
if (new == NULL)
{
printf("cons: out of memory\n");
abort();
}
new->first = v;
new->rest = lst;
new->prev = NULL;
new->rest->prev = new;//updating the previous list this is where I'm confused
//lst->rest =new;
return new;
}
The header looks like
Code:
struct node {
int first;
struct node *rest;
struct node *prev;
};
struct node *cons(int v, struct node *lst);
void add_after(int v, struct node *nptr);
struct node *remove_first(struct node *lst, int key);
Any help would be appreciated. This is a homework assignment so I don't just want code in return. Thanks. I'd ask a T.A but...its the weekend