| Uutiset | Koodikirjasto | Wiki | Keskustelut | FAQ | Info |
linkitettylistaweicco 27.08.02 13:12 Geneerinen linkitetyn listan minitoteutus, ei mitään ihmeellistä.
/**************** * WLIST.H tiedosto * ****************/ #include <stdlib.h> int AddNode(void *data); void *GetNode(int index); void DelNode(int index); int CountNodes(void); void DelNodes(void); typedef struct _w_node_t { struct _w_node_t *next; void *data; } WNode, *pWNode; /**************** * WLIST.C tiedosto * ****************/ #include "wlist.h" static pWNode list_head = NULL; int AddNode(void *data) { pWNode ptr = list_head; pWNode newNode = (pWNode)malloc(sizeof(WNode)); if (newNode == NULL) return -1; newNode->next = NULL; newNode->data = data; if (ptr == NULL) { list_head = newNode; return 0; } while (ptr->next != NULL) ptr = ptr->next; ptr->next = newNode; return 0; } void *GetNode(int index) { pWNode ptr = list_head; while (ptr != NULL && index - 1 > 0) { ptr = ptr->next; index--; } return (ptr != NULL ? ptr->data : NULL); } void DelNode(int index) { pWNode ptr = list_head; pWNode prv = NULL; while (ptr != NULL && index - 1 > 0) { prv = ptr; ptr = ptr->next; index--; } if (ptr == NULL) return; if (prv == NULL) list_head = ptr->next; else prv->next = ptr->next; free(ptr); } int CountNodes(void) { pWNode ptr= list_head; int n = 0; while (ptr != NULL) { ptr = ptr->next; n++; } return n; } void DelNodes(void) { int nmax = CountNodes(); for (int n = 0 ; n < nmax ; n++) DelNode(n); } Torak 12:08 28.8.02 No nyt oli testattava tätä kommentointi osuuttakin :) int AddNodeSort(void *data) { pWNode node = NULL; struct WNode ** ppScan = &list_head; pWNode newNode = (pWNode)malloc(sizeof(WNode)); if (newNode == NULL) return -1; while(*ppScan != NULL && compare(*ppScan, node)) ppScan = &(*ppScan)->next; node->next = *ppScan; *ppScan = node; } weicco 09:30 10.9.02 Käyttäjän oma tehtävä on tuhota ne tiedot listasta, en minä niitä voi tuhota. Kuvitellaanpa, että lista sisältää struktuurin, jossa on 5 kpl c-stringejä dynaamisesti varattuna. Jos tuhoan sen struktuurin, ei niitä 5 stringiä saada koskaan tuhottua. Staattinen muuttuja... Huomaa, että se on globaali staattinen, joka on hieman eriasia kuin lokaali staattinen. Muuten olet kyllä oikeassa. Jos halutaan useampi lista, täytyisi tehdä erillinen ListStart funktio, joka palauttaisi pointterin listaan ja kaikille *Node* funtioille pitäisi antaa tuo pointteri. Taidanpa toteuttaa moisen ja postata sen tänne kunhan kerkeän. Antti 19:32 24.3.03 Oh, void *data; eipä o tullu tollasta mieleen :-( Antti 19:34 24.3.03 Mä oon itte tehnyt aina kaikille omat structit ja linkit yksitellen. |
![]() Haku
|