// What is this typedef to a pointer for? How does this work?
Whenever you say ListNode, you actually mean struct listnode *, which is confusing because ListNode doesn't suggest that it's a pointer at all, and the rest of your code gets confused because of it. Change the struct declaration to this:
Code:
typedef struct listnode{
int data;
struct listnode *next;
}Listnode;
Then you can declare pointers of Listnode without getting tripped up by a hidden level of indirection. But that means you need to change the rest of the code to use dual indirection so that your changes stick when made inside a function:
Code:
#include<stdio.h>
#include<stdlib.h>
// What is this typedef to a pointer for? How does this work?
typedef struct listnode{
int data;
struct listnode *next;
}Listnode;
void printmenu();
int insert( Listnode **, int );
void printlist( Listnode * );
int main()
{
int mode = 0;
Listnode *start = NULL;
int data = 0;
printmenu();
while( 1 ) {
printf( "\nEnter Command:" );
scanf( "%d", &mode );
if( mode == 1 ){
printf( "\n Enter Data:" );
scanf( "%d", &data );
insert( &start, data );
printlist( start );
}
else if( mode == 2 ){
}
else return 0;
}
return 0;
}
void printmenu()
{
printf( "\n\n1 - Insert Data\n"
"2 - Delete Data\n"
"3 - Exit Simulation\n\n" );
}
int insert( Listnode **startPtr, int idata )
{
Listnode *newPtr, *prevPtr, *curPtr;
newPtr = malloc( sizeof( Listnode ) );
newPtr->data = idata;
newPtr->next = NULL;
prevPtr = NULL;
curPtr = *startPtr;
while( curPtr != NULL && idata > curPtr->data ){
prevPtr = curPtr;
curPtr = curPtr->next;
}
if( prevPtr == NULL ){
newPtr->next = *startPtr;
*startPtr = newPtr;
}
else{
prevPtr->next = newPtr;
newPtr->next = curPtr;
}
return 0;
}
void printlist( Listnode *startPtr )
{
if( startPtr == NULL )
printf( "\n The List is Empty (%d)\n", startPtr->data );
else{
while( startPtr != NULL ){
printf( "-->%d", startPtr->data );
startPtr = startPtr->next;
}
printf( "-->NULL\n" );
}
}
this part within this bracket is kinda confusing.. can someone explain this to me please? Lest say its the first run of the program startPtr is currently pointing at nothing... newPtr-> will be pointing at starPtr, thats fine but then startPtr points to new Ptr right? hows that gonna work?
That code sticks the new node into the front of the list by pointing the new node to the current front of the list, then setting the front of the list to point to the new node.