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

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

Node * head = NULL;

while ( still data ) {

 head = List_insert ( head , data );

}

OR

do {

 scanf ( "%d", &value );
 if ( value != 0 )
 {
   head = List_insert ( head, value );
 }

} while ( value != 0 );

=> All of the data in the list.

Node * List_search ( Node *p, int v ) {

 while ( p != NULL )
 {
   if ( p -> value == v )
   {
      return p;
   }
   p = p -> next;
 }
 return p; /* OR NULL */

}



Alumni Liaison

has a message for current ECE438 students.

Sean Hu, ECE PhD 2009