Thread: 4th C Program

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Feb 2009
    Posts
    25

    4th C Program

    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
    Last edited by Stormweaver1; 03-14-2009 at 08:12 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Issue with program that's calling a function and has a loop
    By tigerfansince84 in forum C++ Programming
    Replies: 9
    Last Post: 11-12-2008, 01:38 PM
  2. Need help with a program, theres something in it for you
    By engstudent363 in forum C Programming
    Replies: 1
    Last Post: 02-29-2008, 01:41 PM
  3. Replies: 4
    Last Post: 02-21-2008, 10:39 AM
  4. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  5. My program, anyhelp
    By @licomb in forum C Programming
    Replies: 14
    Last Post: 08-14-2001, 10:04 PM