Solved

linked list

Posted on 2003-11-13
5
904 Views
Last Modified: 2013-12-14

this is a program which you can add and remove phone no and names however it has got errors I would appreciate if you can show me my errors
the delete part does not work and the insert part works a little bit strange even though I looked for this I could not found out
I will be very happy if you can send me web addresses of linked list handlings ...


#include <stdio.h>
#include <stdlib.h>
struct phone_book {
              char name [25];
              char phone_no[15];
             struct phone_book *next;
}*sptr;
void insert (struct phone_book *record);
void print (struct phone_book *record);
void delete (struct phone_book *record);
void instructions( void )

{
   printf( "Enter your choice:\n"
          "   1 to insert an element into the list.\n"
          "   2 to delete an element from the list.\n"
          "   3 to end.\n" );
}



void main () {
        int choice;
            struct phone_book *head,*current;
            head = (struct phone_book *) malloc(sizeof(struct phone_book));
            current=head;
        instructions();
        printf("enter your choice\n");
        scanf("%d\n",&choice);
        while ( choice != 3 ) {

      switch ( choice ) {
         case 1:
         insert (current);
            current->next=(struct phone_book *)                                    
            malloc(sizeof(struct phone_book));
            current=current->next;
                current->next=NULL;
            print (head);
          break;
 
         
           
            default:
            printf( "Invalid choice.\n\n" );
            instructions();
            break;
            case 2:
            delete();
            break;
            }
            }
            }


 

void insert (struct phone_book *record)
{
      char name;
      int phone_no;
      printf("Enter name\n");
      gets(record->name);
      printf("Enter number\n");
      gets(record->phone_no);
      return;
}



void print (struct phone_book *head)
{
while( head != NULL) {
      printf("%s\t%s\n", head->name, head->phone_no);
      head=head->next;
      }
}
void delete(struct phone_book *record))
{
int tempptr;
int * sptr;
printf("enter the number to be deleted");
scanf("%s",&phone_no);
      if (phone_no==(*sptr)->num) {
      tempptr=*sptr;
      *sptr=(*sptr)->nextptr;
      free(tempptr);
      
      }
}
0
Comment
Question by:hermesc
  • 2
5 Comments
 
LVL 23

Assisted Solution

by:brettmjohnson
brettmjohnson earned 250 total points
ID: 9744667
The code does not compile, but I assume you know that.  I have reformatted the code a bit, so the
line numbers below will not match up to yours, but that should not be too much of a problem.

> llist.c: In function `main':
> llist.c:46: error: too few arguments to function `delete'

In case 2: of your switch statement you call delete(), but you do not pass any node to delete.


llist.c: In function `insert':
llist.c:59: warning: unused variable `name'
llist.c:60: warning: unused variable `phone_no'

Obvious.  You declare two variables that you never use.


llist.c: In function `delete':
llist.c:83: error: `phone_no' undeclared (first use in this function)
llist.c:83: error: (Each undeclared identifier is reported only once
llist.c:83: error: for each function it appears in.)
llist.c:84: error: invalid type argument of `->'
llist.c:86: error: invalid type argument of `->'
llist.c:87: warning: passing arg 1 of `free' makes pointer from integer without a cast

Well, this routine is a mess.  We will have to go over it line-by-line:

void delete(struct phone_book *record)
{
  int tempptr;
  int * sptr;
  printf("enter the number to be deleted");

So far, nothing offensive

  scanf("%s",&phone_no);

This is the phone_no undeclared error.  You probably wanted to declare a local char buffer to
hold the phone number string:  char phone_no[15];  However scanf could overflow this buffer,
so you might change the scanf format string to  scanf("%15s", &phone_no);

  if (phone_no==(*sptr)->num) {

There is so much wrong with this line:
 - sptr is an uninitialized pointer, so dereferencing it will generate a segmentation fault.
 - sptr is a pointer to an integer, not a structure, so (*ptr)->num makes no sense.
 - you are apparently comparing a string to an integer.
 - using == to compare equality of strings is almost never what you want.  == will compare
the addresses of the strings, not the contents.  You probably want to use strcmp to compare
the values of the strings.
 - you most likely want to iterate over the linked list comparing the specified phone number
to the phone number of each record.  So this comparison should probably be in a loop.

    tempptr=*sptr;
    *sptr=(*sptr)->nextptr;

Again, sptr is a pointer to an int.  It looks like you meant it to be a pointer to a linked list node,
however, the structure members num and nextptr don't match up to the phone_book structure
you have defined.  You have 30% of the advanced C trick deleting a node from a singly linked list
in hand.

    free(tempptr);
  }
}
0
 
LVL 45

Accepted Solution

by:
Kdo earned 250 total points
ID: 9744705
Ok.  First of all, linked lists aren't hard -- don't let them intimidate you.  :)

Your insert() function doesn't really insert anything into the list.  Likewise, the delete() function doesn't really do a delete.  But it's easy to make them do what you want.  I'll provide you with the tools to do the add and delete, and you can plug them into your program.

The first thing that needs to be done is change the program flow.  In main, you need to insert a loop that reads from the input file and calls insert() for every record that is read.  You can also write another function for this (something like LoadDataFile()), have the new function perform this read loop, and just have main call the new function.

To insert the new record, you have to decide where you want it placed in the list.  Will it be the first record?  Will it be inserted at the end?  What about inserting the record so that it winds up in alphabetical order?

To insert the record, we'll need to first create a new record (struct) from the data that was read from the file.

struct phone_book *phone_book_entry;

phone_book_entry = (phone_book_entry *)malloc (sizeof (phone_book));
strcpy (phone_book_entry->name, Name);
strcpy (phone_book_entry->phone_no, PhoneNumber);

Note that Name and PhoneNumber were read from your input file.  You probably want to use fscanf() to get the data from the input record into these two variables.

Now to insert it at the beginning is the easiest.  All we do is set the *next* pointer in the new record to point to the existing chain and then set *head* to point to our new node.  If *head* was NULL, meaning that there was nothing on the list, then the *next* pointer in our record is set to NULL which will mean that it is also the last record on the list.

phone_book_entry->next = head;
head = phone_book_entry;


Inserting the record at the end is only a couple of more lines of code:

/* this line advances *current* to the last member in the list  */
for (current = head; current != NULL && current->next &= NULL; current = current->next);

if (current == NULL)
  /* current is NULL which means that head was null so we add the node at the front of the list  */
else
{
  current->next = phone_book_entry;
  phone_book_entry->next = NULL;
}


Finally, to add the entry at a particular place in the list, we loop through the list until we get to the correct spot.  The for(;;) statement above looped to the end of the list.  Changing the loop condition of the statement can make the loop stop wherever you want it to stop.  Please note that when the loop stops, current needs to point to the element BEFORE the place you want to insert the node so that you can properly establish the *next* pointers.

I'll leave the last one up to you.


Good Luck!
Kent
0
 
LVL 45

Expert Comment

by:Kdo
ID: 9760320

The thread originator posted a problem that, based on his own attempt to esolve, indicated that he clearly didn't understand the subject matter.

Within an hour, two experts (working independently and simultaneously) post lengthy and informative explanations that describe the problems and offer good advice as to how to fix them.  Clearly, the original poster received direction from somewhere.  The claim that he went from no understanding of the subject matter to complete understanding without help defies belief.

I'm opposed to the refunding of points for this question.  Discard them, award them to the first posted response or split them between the two experts that offered good advice.


Kent
0
 

Author Comment

by:hermesc
ID: 9760396
Ok I split those points ....

I have to explain the event befor I post the question I was a stranger to the subject and I was mixed totally. I admit the answers were good but I have not used them since I worked again this subject from my notes and find out a suitable answer for myself .The only reason for not giving the points is this.I respect the work which experts have done but there are a lot of experts who provide a lot of good answers and get nothing but another person gets the point.I think this is the way it goes here. Maybe you have the best answer but another answer fits better.Arent I right?
I will give points since you think that you believe that you have done good job ( moreover I do not need points so refunding points are not important for me )And I would like to apologize if IO have done something wrong here ( I am very new here)
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode (http://en.wikipedia.org/wiki/Unicode)? They will have you believe that Unicode requires you to use…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use while-loops in the C programming language.
The goal of this video is to provide viewers with basic examples to understand opening and reading files in the C programming language.

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now