Tutorial Exercises Week 1

Exercise 1 - Linked Lists

  1. Consider the material on linked lists that we discussed in the lecture with the following definition (Item is a char now):

    typedef char Item;
    
    typedef struct node *link;
    
    struct node {
      Item item;
      link next;
    };
    

    Write the following functions:

  2. Assume we have a function printList which, given a list of characters, prints each character, and a function `cstrToList` which converts a regular C string (i.e., `\0` terminated array of characters) into a list of characters. What is the output of the following program? (See implementation of reverse in Exercise 2.)

    int main (int argc, const char * argv[]) {
      link ls = cstrToList ("hello world!");
      link ls2 = duplicate(ls);
      printList (ls);
      printList (ls2);
      printList (reverse (ls));
      printList (ls);
      printList (ls2);
      return 0;
    }
    

Exercise 2 - Linked Lists, an alternative implementation

Exercise 3 - Double linked lists

In the lecture, we briefly discussed doubly linked lists.

typedef char Item;

typedef struct dnode *dlink;

struct dnode {
    Item  item;
    dlink next;
    dlink prev;
};

Write a function

dlink append (dlink list1, dlink2 list2)

which attaches the list list2 at the end of list1 and returns the resulting list.

Is it necessary to return the resulting list, or would the following interface work (as list1 is altered)

void append (dlink list1, dlink list2)