Struct+List ++
.pdfInsert Item to sorted list: before & after
LIST* InsertSortedList(LIST *&head, LIST *&end, int z) { LIST *p=head,*q,*s;
while(p && z<p->x) { q=p; p=p->next; }
s=(LIST *) malloc(sizeof(LIST)); s->x=z;
if(!head) { s->prev=0; s->next=0; head=s; end=s;} else if(p==head) { s->prev=0; s->next=p; head=s; } else if(p==0) { s->prev=q; s->next=0; end=s; } else
{ s->prev=q; s->next=p; }
return p;
21
}
Insert item to head
LIST *InsertHead(LIST *&head, int z) { LIST *q;
q=(LIST *) malloc (sizeof (LIST)); q->x=z;
q->prev=0; q->next=head; if(head) head->prev=q; head=q; return q;
}
22
Insert item to end = tail
LIST *InsertTail(LIST *&head, LIST *&end, int z)
{LIST *p=head,*q; if(!p) goto create; while(p->next) p=p->next; create:
q=(LIST *) malloc (sizeof(LIST)); q->x=z;
q->prev=p; q->next=0; if(p) p->next=q; end=q;
return q;
} // InsertTail
23
Insert to end
LIST * InsertEnd(LIST *end, int z) { LIST *q;
q=(LIST *) malloc(sizeof(LIST)); q->x=z;
q->prev=end; q->next=0; if(end) end->next=q; return q;
} // InsertEnd
24
Delete Item
p->prev p p->next
25
Delete Item
|
LIST *DeleteItem(LIST *&head, LIST *&end, int z) |
|
{ |
LIST *p=head; |
|
|
while(p) |
|
{ |
if(z==p->x) break; |
|
|
p=p->next; |
|
} |
|
|
|
if(!p) return 0; // не нашёл |
|
|
if(p->prev==0) { head=p; p->next->prev=0;} // он первый |
|
|
else p->prev->next=p->next; |
|
|
if(p->next==0) // он последний |
|
|
{ end=p->prev; p->prev->next=0; } |
|
|
else p->next->prev=p->prev; |
|
|
free(p); return p; |
|
} |
// DeleteItem |
26 |
|
|
Delete List
int DeleteList(LIST *&head) { LIST *p,*q=head; int i=0;
while(q) { p=q;
q=p->next; free(p); i++;
}
head=0; return i;
} |
27 |
|
|
Print List |
|
|
int |
PrintList(LIST *head) |
|
{ |
int |
i, z; LIST *p = head; |
|
|
if(!p) { printf("Your LIST is not \n"); return 0; } |
|
|
|
printf("Your LIST is: \n"); |
|
|
|
for(i=0; p; i++) |
|
|
{ |
z=p->x; |
|
|
|
printf("%i %p %i \n", i , p, z); |
|
|
|
p=p->next; |
|
|
} |
|
|
|
|
printf("\n"); |
|
|
|
return i; |
|
|
} |
// PrintList |
28 |
|
|
|
|
|
|
|
|
|
List to File & Delete List
int ListToFile(LIST *head, char fileOS[])
{ int i, j=0, k, m; LIST *q, *p = head; FILE *f; m=sizeof(LIST);
f=fopen(fileOS,“a+b"); // rewind(f); for(i=0; p; i++)
{ k=fwrite(p, m, 1, f); j=j+k;
q=p; p=p->next; free(q);
}
fclose(f); return j;
} // ListToFile
29
FileToList
int FileToList(LIST *&head, char fileOS[])
{int i, k, j=0, m; FILE *f ; LIST *p=0, *q=0; m=sizeof(LIST);
f=fopen( fileOS, "a+b"); rewind(f); // -> begin
for(i=0; ; i++)
{ p=(LIST*)calloc(1,m); k=fread(p, m, 1, f); j = j+k; if(feof(f)) break;
if(i==0) head=p; p->next=0; p->prev=q; if(i>0) q->next=p; q=p;
}
fclose(f); return j;
} // FileToList |
30 |
|