class List // I want to use 1 prgram file for this example, so I put the List class here... { int value; List next; } public class insert { /* ========================================= insert(h, e): insert e at start of list h return new list A List variable is a reference variable !!! ========================================= */ public static List insert (List h, List e) { e.next = h; return e; // Return new list that starts at e } public static void main(String[] args) { List head = null; // Empty list List p; /* ------------------------------------------------- Create a list element and insert in List at head ------------------------------------------------- */ p = new List( ); p.value = 1; head = insert(head, p); // Insert p in head print(head); /* ------------------------------------------------- Create a list element and insert in List at head ------------------------------------------------- */ p = new List( ); p.value = 2; head = insert(head, p); // Insert p in head again print(head); } // 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"); } } |
How to run the program:
|
Here is the C program code for the above Java program:
#include <stdio.h>
#include <stdlib.h>
struct List // This is the List class definition in C
{
int value;
struct List *next;
};
/* =========================================
insert(h, e): insert e at start of list h
return new list
The data type List is struct List * in C
========================================= */
struct List *insert (struct List *h, struct List *e)
{
e->next = h;
return e; // Return new list that starts at e
}
void print(struct List *h); // We must declare print to avoid compile error
void main(int argc, char *argv[])
{
struct List *head = NULL; // Nul pointer NULL instead of null
struct List *p;
/* -------------------------------------------------
Create a list element and insert in List at head
------------------------------------------------- */
p = malloc( sizeof(struct List) );
p->value = 1;
head = insert(head, p); // Insert p in head
print(head);
/* -------------------------------------------------
Create a list element and insert in List at head
------------------------------------------------- */
p = malloc( sizeof(struct List) ); // This is new List( )
p->value = 2;
head = insert(head, p); // Insert p in head
print(head);
}
// Print the list
void print(struct List *h)
{
while (h != NULL)
{
printf("%d ", h->value);
h = h->next;
}
printf("\n\n");
}
|
It literally took me 2 minute to convert the Java code to C code....
How to run the program:
|
|