Revision as of 04:48, 27 March 2012 by Jribeir (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Lecture 19 - 3/27 - John Ribeiro - Lu

typedef struct listnode {

 struct listnode *next; // don't forget *
 int value;

} Node;

Node * Node_construct ( int n ) {

 Node * n;
 n = malloc ( sizeof ( Node ) );
 n -> next = NULL; // Very common mistake to forget this
 n -> value = v;
 return n;

}

Node * List_insert ( Node * head, int v ) {

 Node * n = Node_construct ( v );
 n -> next = head; // Key to how the linked list works
 return n;

}

// The insertion is like a stack, first in, last out

void List_print ( Node * head ) {

 Node * p = head;
 while ( p != NULL )
 {
   printf ( " %d \n ", p -> value );
   p = p->next;
 }

}

void List_destroy ( Node * head ) {

 Node * p;
 Node * q;
 p = head;
 while ( p != NULL )
 {
   q = p ->next;
   free ( p );
   p = q;
 }

}

How to use this?

Node * head = NULL; // Must Initialize head = List_insert ( head, 6 ); head = List_insert ( head, 29); head = List_insert ( head, -74 ); List_print ( head ); List_destroy ( head ); head = NULL; // Must redefine head to point to NULL



Alumni Liaison

BSEE 2004, current Ph.D. student researching signal and image processing.

Landis Huffman