|
|
To write a C function, you need to express the algorithm (a concept !) with C syntax
|
Next: public class ....
|
Next: the parameters and return value
|
Next: the expression h.next
|
Next: the expression null
|
Done.... wait.... done ?
class List // Class included to make 1 program file
{
int value;
List next;
}
public class delete
{
/* ====================================================
delete(h): delete the first elem from the list h
return new list
==================================================== */
public static List delete (List h)
{
if ( h != null )
return (h.next); // Return new list that starts at h.next
else
return null;
}
public static void main(String[] args)
{
List head = null;
// Insert 10 elements
for (int i = 1; i <= 10; i++)
{
List e = new List();
e.value = i;
head = insert(head, e); // Insert i at head
print(head);
}
// Delete 10 elements
for (int i = 1; i <= 10; i++)
{
head = delete(head); // Delete at head
print(head);
}
}
public static List insert (List h, List e)
{
e.next = h;
return e; // Return new list that starts at e
}
// Print the list
public static void print(List h)
{
while (h != null)
{
System.out.printf("%d ", h.value);
h = h.next;
}
System.out.printf("\n\n");
}
}
|
DEMO: demo/C/Linked-list/delete.java
I will "convert" the program in class as a demo
#include <stdio.h>
#include <stdlib.h>
struct List
{
int value;
struct List *next;
};
void print(struct List *h); // Declaration
struct List *insert (struct List *h, struct List *e);
/* ====================================================
delete(h): delete the first elem from the list h
return new list
==================================================== */
struct List *delete (struct List *h)
{
if ( h != NULL)
return h->next;
else
return NULL;
}
int main(int argc, char *argv[])
{
struct List *head = NULL;
// Insert
for (int i = 1; i <= 10; i++)
{
struct List *e = malloc( sizeof(struct List) ) ;
e->value = i;
head = insert(head, e); // Insert i at head
print(head);
}
// Delete
for (int i = 1; i <= 10; i++)
{
head = delete(head); // Delete at head
print(head);
}
}
// Insert at head
struct List *insert (struct List *h, struct List *e)
{
e->next = h;
return e; // Return new list that starts at e
}
// Print the list
void print(struct List *h)
{
while (h != NULL)
{
printf("%d ", h->value);
h = h->next;
}
printf("\n\n");
}
|
Now run this modified program using (ulimit -v 50000; a.out > err)
int main(int argc, char *argv[])
{
struct List *head = NULL;
int c = 0;
while(1) // Infinite loop...
{
printf("%d\n", ++c); // Keep a count
// Insert
for (int i = 1; i <= 10; i++)
{
struct List *e = malloc( sizeof(struct List) ) ;
e->value = i;
head = insert(head, e); // Insert i at head
print(head);
}
// Delete
for (int i = 1; i <= 10; i++)
{
head = delete(head); // Delete at head
print(head);
}
}
}
|
DEMO: demo/C/Linked-list/delete2.c
|
|
|
|
DEMO: demo/C/Linked-list/delete3.c