Revision as of 02:58, 31 March 2012 by Song110 (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 */

}



Lecture 20 3/27 _ Kailu Song

(Application of link list) typeof struct listnode { struct list node *next; int value; }Node;

Node *Node_construct (int u) { Node *n; n = malloc(sizeof(Node)); n -> next = NULL; n->value = u; return n; } Node *List_insert(Node *h, int v) { Node *n = Node_construct(v); n -> next = h; return n; }

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

void List_destroy (Node *h) { Node *p; Node *q;

	p = h;

while (p!= NULL) { q = p->next; free℗; p = q; } }

void main() { Node *head = NULL; head = List_insert(head,6); head = List_insert(head,29); head = List_insert(head,-74); List_printf(head); List_destroy(head); head = NULL; }

Alumni Liaison

Ph.D. on Applied Mathematics in Aug 2007. Involved on applications of image super-resolution to electron microscopy

Francisco Blanco-Silva