|
From: Per W. <pw...@ia...> - 2007-06-08 17:11:48
|
No need for any extra allocation.
You are making an extra assign:
temp = q;
temp -> next = q -> next;
Note that after the first assign, temp and q will have the same value,
i.e. point to the same memory. temp->next and q->next is not two different
fields. It's the same memory, so the second assign is about as useful as
writing:
foo = foo;
A little trick when working with single-lined lists:
Don't make the last element in the list have a next = NULL;
Don't keep track of the list with a pointer front.
Instead make the list circular, and keep track of the list with a pointer
named last or tail.
Note that if the list is empty, last will be NULL.
If the list is not empty, last->next will point to the first entry in the
list.
This way, you will be able to access both the first and the last element
in the list in constant time. You will also be able to insert new elements
either first or last, without the need to loop through the list.
/pwm
On Fri, 8 Jun 2007, Jan Mura wrote:
> Hello,
>
> I would like to ask about some things in linked list I
> try to write.
> It looks like:
>
> struct s
> {
> int id;
> char *name;
> struct s *next;
> };
>
> int main ()
> {
> struct s *front = NULL; /*the front of a list */
> int i = 1;
> char *name;
>
> while (1)
> {
> gets (name);
> if (strlen(name) == 0) break;
> in_list (&front, i, name);
> i++;
> }
> return 0;
> }
>
> void in_list (struct s **q, int in_id, const char *in_name)
> {
> struct s*member, *temp;
>
> member = malloc (sizeof (struct s));
> member -> name = malloc (strlen (in_name) +1);
>
> member-> id = in_id;
> strcpy (member -> name, in_name);
> member -> next = NULL; /* it will be the last member in the list */
>
> if (q == NULL) /* empty list */
> {
> q = member;
> q -> next = NULL;
> }
> else
> {
> temp = q;
> temp -> next = q -> next;
>
> while (temp -> next != NULL)
> temp = temp -> next; /* looking for the last member in the list */
>
> temp ->next = member; /* the last member is no more the last one */
> }
> }
>
> Should I allocate the space for temp and temp -> next when I am
> putting an adress from member to temp?
>
> So should it looks like:
>
> temp = malloc ...;
> temp = member;
> ???
>
> Thanks for your answer.
>
> Jan Mura
> jan...@vo...
>
> -------------------------------------------------------------------------
> This SF.net email is sponsored by DB2 Express
> Download DB2 Express C - the FREE version of DB2 express and take
> control of your XML. No limits. Just data. Click to get it now.
> http://sourceforge.net/powerbar/db2/
> _______________________________________________
> Dev-cpp-users mailing list
> Dev...@li...
> TO UNSUBSCRIBE: http://www23.brinkster.com/noicys/devcpp/ub.htm
> https://lists.sourceforge.net/lists/listinfo/dev-cpp-users
>
|