35
Structures and Lists (and maybe stacks) Chapters 9-10

Structures and Lists (and maybe stacks) Chapters 9-10

  • View
    230

  • Download
    0

Embed Size (px)

Citation preview

Structures and Lists(and maybe stacks)

Chapters 9-10

These are equivalentThese are equivalent

Struct definitionStruct definition

Structsstruct card

{

int pips;

int suit;

};

struct card c1, c2;

struct card

{

int pips;

int suit;

} c1, c2;

Varaible declarationVaraible declaration

Structs

c1.pips = 3;

c1.suit = 's';

c2 = c1;

typedef struct card card;

card c3, c4, c5;

Structs

struct fruit

{

char *name;

int calories;

};

struct vegtable

{

char *name;

int calories;

};

struct fruit a;

struct vegtable b;

Structs

struct card{

int pips;int suit;

} desk[52];

---------------------------------struct {

int day, month, year;char day_name[4];char month_name[4];

} yesterday, today, tomorrow;

Structs

typedef struct

{

float re;

float im;

} complex;

complex a, b, c[100];

in the header file: “class_info.h”

#define CLASS_SIZE 100

struct student

{

char *last_name;

int student_id;

char grade;

};

in a source file

#include "class_info.h"

int main( void )

{

struct student tmp, class[CLASS_SIZE];

.....

tmp.grade = 'A';

tmp.last_name = "Casanova";

tmp.student_id = 9100017;

Using the structs and definitions from the h file

Using the structs and definitions from the h file

and in another source file

#include "class_info.h"

int fail( struct student class[] )

{

int i = 0, cnt = 0;

for ( i = 0; i < CLASS_SIZE; ++i )

cnt += class[ i ].grade == 'F';

return cnt;

}

Count the number of failing gradesCount the number of failing grades

in the header file: “complex.h”

struct complex

{

double re;

double im;

};

typedef struct complex complex;

real partreal part

imaginary partimaginary part

#include "complex.h"

void add( complex *a, complex *b, complex *c )

{

a → re = b → re + c → re;

a → im = b → im + c → im;

}

Accessing a struct data member from a pointer: ->

(the → is just for the presentation!)

Accessing a struct data member from a pointer: ->

(the → is just for the presentation!)

a = b + ca = b + c

Declarations and Assignmentsstruct student tmp, *p = &tmp;

tmp.grade = 'A';

tmp.last_name = “Casanova”;

tmp.student_id = 9100017;

Expression Equivalent Expression Value

tmp_grade p → grade A

tmp_last_name p → last_name Casanova

( *p ).student_id p → student_id 9100017

*p → last_name + 1 ( *( p → last_name ) ) + 1 D

*( p → last_name + 2 ) ( p → last_name )[ 2 ] s

Passing Structs

empolyee_data update ( empolyee_data e )

{

.....

prinf( “Input the department number: ” );

scanf( “%d”, &n );

e.department.dept_no = n;

.....

return e;

}

e is a copy of the original struct

e is a copy of the original struct

the local struct is modified

the local struct is modified

the copy is returnedthe copy is returned

void update ( empolyee_data *p )

{

.....

prinf( “Input the department number: ” );

scanf( “%d”, &n );

p → department.dept_no = n;

.....

}

empolyee_data e;

update(&e);

Passing Structs

a pointer to the original struct is passed

a pointer to the original struct is passed

the original struct is modified

the original struct is modified

Initializationcard c = { 13, ‘h’ };

complex a[3][3] =

{

{ { 1.0, -0.1 }, { 2.0, 0.2 }, { 3.0, 0.3 } },

{ { 4.0, -0.4 }, { 5.0, 0.2 }, { 6.0, 0.6 } },

};

struct fruit frt = { “plum”, 150 };

the king of heartsthe king of hearts

a[ 2 ][ ] is assigned zerosa[ 2 ][ ] is assigned zeros

Initialization

struct home_address

{

char *street;

char *city_and_state;

long zip_code;

} address = { “87 wost street”, “aspen, colorado”, 80526 };

struct home_address previous_adress = { 0 };

struct pcard

{

unsigned pips: 4;

unsigned suit: 2;

};

struct abc

{

int a : 1, b : 16, c : 16;

} x;

struct small_integer

{

unsigned i1: 7, i2: 7, i3: 7, : 11, i4: 7, i5 : 7, i6 : 7;

}

a packed representationa packed representation

align to next wordalign to next word

Linked Lists

Self-referential Structures

struct list { int data; struct list * next;};

data next

struct list a,b,c;

a.data = 1;b.data = 2;c.data = 3;a.next = b.next = c.next = NULL;

1 NULL 2 NULL 3 NULL

a.next = &b;

b.next = &c;

1 2 3 NULL

a.next -> next ->data

has the value of 3

in the file: “list.h”#include <stdio.h>

#include <stdlib.h>

#include <assert.h>

typedef char DATA;

struct linked_list

{

DATA d;

struct linked_list *next;

};

typedef struct linked_list ELEMENT;

typedef ELEMENT*LINK;

We will use chars in the exampleWe will use chars in the example

Iterative List Creation

LINK string_to_list( char s[] )

{

int i = 0;

LINK head = NULL, tail = NULL;

if ( s[0] != ‘\0’ )

{

head = ( ELEMENT* )malloc( sizeof( ELEMENT ) );

head→d = s[0];

tail = head;

String is not emptyString is not empty

for ( i=1; s[i] != ‘\0’; ++i )

{

tail→next = ( ELEMENT* )malloc( sizeof( ELEMENT ) );

tail = tail→next;

tail→d = s[i];

}

tail→next = NULL;

}

return head;

}

insert elements at the end of the listinsert elements at the end of the list

mark the end of the listmark the end of the list

Recursive List Creation

LINK string_to_list( char s[] )

{

LINK head = NULL;

if ( s[0] == ‘\0’ )

return NULL;

head = ( ELEMENT* )malloc( sizeof( ELEMENT ) );

head→d = s[0];

head→next = string_to_list( s+1 );

return head;

}

stopping criteriastopping criteria

Printing

void print_list( LINK head )

{

if ( head == NULL )

printf( “NULL\n” );

else

{

printf( “%c → ”, head→d );

print_list( head→next );

}

}

print a list recursivelyprint a list recursively

Countingint count( LINK head )

{

if ( head == NULL )

return 0;

else

return( 1 + count( head→next ) );

}

int count_it( LINK head )

{

int cnt = 0;

for ( ; head !=NULL; head = head→next )

++cnt;

return cnt;

}

count a list recursivelycount a list recursively

count a list iterativelycount a list iteratively

Concatenate Lists

void concatenate( LINK a, LINK b )

{

assert(a != NULL);

if ( a→next == NULL )

a→next = b;

else

concatenate( a→next, b );

}

concatenate lists a & b, with list a as the head

concatenate lists a & b, with list a as the head

insert

void insert( LINK p1, LINK p2, LINK q )

{

assert( p1→next == p2 );

p1→next = q;

q→next = p2;

}

Stack

An implementation of type Stack#define MAX_LEN 1000

#define EMPTY -1

#define FULL ( MAX_LEN – 1 )

typedef enum boolean

{

false = 0,

true

} boolean;

typedef struct stack

{

char s[ MAX_LEN ];

int top;

} stack;

An implementation of type Stackvoid reset( stack *stk )

{

stk → top = EMPTY;

}

void push( char c, stack *stk )

{

stk → top++;

stk → s[ stk → top ] = c;

}

char pop(stack *stk)

{

return ( stk → s[ stk → top-- ] );

}

Make the stack emptyMake the stack empty

Push a char onto the stackPush a char onto the stack

Pop a char off the top of the stackPop a char off the top of the stack

char top( stack **stk )

{

return ( stk → s[ stk → top ] );

}

boolean empty( const stack *stk )

{

return ( ( boolean ) ( stk → top == EMPTY ) );

}

boolean full( const stack *stk )

{

return ( ( boolean ) ( stk → top == FULL ) );

}

An implementation of type Stack

The char at the top of the stackThe char at the top of the stack

Return true if emptyReturn true if empty

Return true if fullReturn true if full

Test the Stack implementation by Reversing a String

#include <stdio.h>

#include “stack.h”

int main(void)

{

char str[] = “My name is Laura Poh!”;

int i = 0;

stack s;

reset( &s );

printf( “In the string %s\n”, str );

Make the stack emptyMake the stack empty

Test the Stack implementation by Reversing a String

for ( i - 0; str[i] != '\0'; ++i )

{

if ( !full( &s ) )

push(str[i], &s);

}

printf( “From the stack: ” );

while ( !empty( &s ) )

{

putchar( pop( &s ) );

}

putchar ('\n');

return 0; In the tring : My name is Laura Poh!

} From the stack: !hoP aruaL is eman yM

push a char onto the stackpush a char onto the stack

check that the stack is not fullcheck that the stack is not full

check that the stack is not emptycheck that the stack is not empty

pop a char off the stackpop a char off the stack