home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #26 / NN_1992_26.iso / spool / comp / lang / c / 16066 < prev    next >
Encoding:
Internet Message Format  |  1992-11-07  |  2.1 KB

  1. Path: sparky!uunet!cis.ohio-state.edu!zaphod.mps.ohio-state.edu!sol.ctr.columbia.edu!spool.mu.edu!agate!doc.ic.ac.uk!uknet!strath-cs!ps
  2. From: ps@cs.strath.ac.uk (Paul Shaw)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Link Lists - Malloc - Help
  5. Message-ID: <10887@baird.cs.strath.ac.uk>
  6. Date: 6 Nov 92 08:30:59 GMT
  7. References: <1992Oct27.220720.3645@stortek.com> <2178@ontek.com> <Bx72EG.9JG@sci.kun.nl>
  8. Organization: Comp. Sci. Dept., Strathclyde Univ., Glasgow, Scotland.
  9. Lines: 64
  10.  
  11. In article <Bx72EG.9JG@sci.kun.nl> hansm@cs.kun.nl (Hans Mulder) writes:
  12. >In <2178@ontek.com> mikey@ontek.com (euphausia superba) writes:
  13. >
  14. >You _can_ avoid making this distinction, if you're willing to throw
  15. >another level of pointers at it:
  16. >
  17. >    zombie = search_list(head);  /* identify item to delete */
  18. >    if (zombie != NULL) {
  19. >        struct item **ptr = &head;
  20. >        while (*ptr != zombie)
  21. >            ptr = &((*ptr)->next);
  22. >        *ptr = (*ptr)->next;
  23. >        free((void*)zombie);
  24. >    }
  25. >
  26. >Is having only one case worth the confusion generated by using pointers
  27. >to pointers?  I really don't know.
  28.  
  29. I don't think so, its not very easy to read.  Why not just do:
  30.  
  31. typedef struct DEMO_LIST {
  32.    /* Other stuff */
  33.    struct DEMO_LIST *next;
  34. }DEMO_LIST;
  35.  
  36. DEMO_LIST *delete_item(l,item) DEMO_LIST *l,*item;
  37. {
  38.    if (l) {
  39.       if (l == item) {
  40.          DEMO_LIST *t;
  41.          t = l->next;   free((void *)l);   return(t);
  42.       }
  43.       else {
  44.          l->next = delete_item(l->next,item);   return(l);
  45.       }
  46.    }
  47.    else {
  48.       /* Getting here means the item did not exist in the list.  You
  49.        * can stick what code you want in here, either return NULL (l) if this
  50.        * is OK or do some error handling stuff.
  51.        */
  52.       return(l);
  53.    }
  54. }
  55.  
  56. Call this code by:
  57.  
  58. list = delete_item(list,item);
  59.  
  60. I also like my list functions returning the new list as this allows things
  61. like:
  62.  
  63. list = delete_item(delete_item(l,item1),item2);
  64.  
  65. I don't want to get into a flame war about recursion and efficiency here, but
  66. certainly to me, the recusive version is easier to read (no complex
  67. dereferences etc.), and more likely to be bug free.
  68.  
  69. Just another view.....
  70.  
  71. Paul Shaw,
  72. Dept of Computer Science,
  73. University of Strathclyde,
  74. Glasgow.
  75.