Exercises 1-7, 18 (use the STL list class) _____________________________________
ID: 3531488 • Letter: E
Question
Exercises 1-7, 18 (use the STL list class)
___________________________________________________________________
Exercises 1-7 assume the following declarations (which are used to process singlylinked
lists):
class Node
{
public:
i nt data;
Node * next;
} ;
Node * pI, * p2, * p3;
Assume also that the following statements have been executed:
pI= new(nothrow) Node;
p2= new(nothrow) Node;
p3= new(nothrow) Node;
Tell what will be displayed by each of the code segments or explain why an error
occurs.
___________________________________________________________________
1. p1->data= 123;
p2->data= 456;
p1->next= p2;
p2->next= 0;
cout
Explanation / Answer
#include #include #include /* structure containing a data part and link part */struct node { int data ; struct node *link ; } ; void append ( struct node **, int ) ; int length ( struct node * ) ; void main( ) { struct node *p ; p = NULL ; /* empty linked list */ append ( &p, 1 ) ; append ( &p, 2 ) ; append ( &p, 3 ) ; append ( &p, 4 ) ; append ( &p, 5 ) ; clrscr( ) ; printf ( "Length of linked list = %d", length ( p ) ) ; } /* adds a node at the end of a linked list */void append ( struct node **q, int num ) { struct node *temp ; temp = *q ; if ( *q == NULL ) /* if the list is empty, create first node */ { *q = malloc ( sizeof ( struct node ) ) ; temp = *q ; } else { /* go to last node */while ( temp -> link != NULL ) temp = temp -> link ; /* add node at the end */ temp -> link = malloc ( sizeof ( struct node ) ) ; temp = temp -> link ; } /* assign data to the last node */ temp -> data = num ; temp -> link = NULL ; } /* counts the number of nodes in a linked list */int length ( struct node *q ) { staticint l ; /* if list is empty or if NULL is encountered */if ( q == NULL ) return ( 0 ) ; else { /* go to next node */ l = 1 + length ( q -> link ) ; return ( l ) ; } }Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.