* Sorted List
@ 2005-11-26 2:28 Nanakos Chrysostomos
0 siblings, 0 replies; 2+ messages in thread
From: Nanakos Chrysostomos @ 2005-11-26 2:28 UTC (permalink / raw)
To: linux-c-programming
Hi ,all.Can someone please explain this source code with an example???
***********************************************************************
#include <stdio.h>
typedef struct list_tag {
int data;
struct list_tag *next;
}ListNode;
typedef ListNode *slist;
slist empty = NULL;
void slistInsert(slist *sp,int t)
{
ListNode *n=(ListNode *)malloc(sizeof(ListNode));
if(n == NULL)
{
printf("Out of memory\n");
exit(1);
}
n->data = t;
while(*sp!=NULL && (*sp)->data < t)
{
sp = &((*sp)->next); //Why we do this here,i miss this point
}
n->next = *sp;
*sp = n;
}
void slistRemove(slist *sp,int t)
{
ListNode *n;
while(*sp!=NULL && (*sp)->data <t)
sp = &((*sp)->next);
if(*sp == NULL)
{
printf("Not found\n");
exit(1);
}
n=*sp;
*sp = (*sp)->next;
free(n);
}
void slistPrint(slist s)
{
ListNode *n;
for(n=s;n!=NULL; n=n->next)
printf("%d\n",n->data);
}
void main()
{
slistInsert(&empty,4);
slistInsert(&empty,8);
slistInsert(&empty,24);
slistInsert(&empty,50);
slistInsert(&empty,20);
slistInsert(&empty,2);
slistRemove(&empty,4);
slistInsert(&empty,18);
slistPrint(empty);
}
Thank you very much in advance.
^ permalink raw reply [flat|nested] 2+ messages in thread
* Re: Sorted List
@ 2005-11-26 12:06 Bharat Jain
0 siblings, 0 replies; 2+ messages in thread
From: Bharat Jain @ 2005-11-26 12:06 UTC (permalink / raw)
To: linux-c-programming
After the while loop "sp" would be containing the address of the node
after
which the new node is to be inserted.
It is done in this way because *sp = *sp->next would modify the global
"empty" pointer which we dont want. "empty" should always point to
first element of the list.
Hope this helps.
^ permalink raw reply [flat|nested] 2+ messages in thread
end of thread, other threads:[~2005-11-26 12:06 UTC | newest]
Thread overview: 2+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2005-11-26 2:28 Sorted List Nanakos Chrysostomos
-- strict thread matches above, loose matches on Subject: below --
2005-11-26 12:06 Bharat Jain
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).