Materi Pertemuan 2 COMP6048 – Data Structure
Introduction to Linked List
· Structure
o Structure is basically a user-defined data type that can store related information (even of different data types) together, while an array can store only entities of same data types.
o It is a collection of variables under a single name.
o The variables within a structure are of different data types and each has a name that is used to select it from the structure.
· Structure Declaration
struct tdata {
int age;
char name[100];
float score;
};
};
notes :
• The code above defines a structure named tdata which has three members: age (int), name (char[]) and score (float).
• Creating a variable of structure is similar to create a variable of primitive data type.
tdata x; // a variable of tdata
tdata arr[100]; // an array of tdata
You also can define a structure as well as declare variables.
struct tdata {
int age;
char name[100];
float score;
} a, b;
struct tdata {
int age;
char name[100];
float score;
};
tdata a;
Structure Asignments
tdata x;
You can use operator . (dot) to access member of x
x.age = 17;
strcpy(x.name, “andi”);
x.score = 82.5;
untuk memanggil atau memasukkan suatu nilai ke member didalam array gunakan . (dot) seperti contoh di atas. Yaitu nama structure .(dot) nama member
Nested Structure
You also can have a structure as a member of another structure
struct profile {
int age;
char name[100];
};
struct student {
struct profile p;
int score;
char grade;
};
Cara pemanggilan/penggunaan :
student x;
x.score = 92;
x.grade = ‘A’;
x.p.age = 20;
strcpy(x.p.name,”budi”);
Array of structure
You also can have an array of structure.
struct profile {
int age;
char name[100];
};
struct student {
struct profile p;
int score;
char grade;
};
Cara pemanggilan/penggunaan :
student arr[10];
arr[0].score = 92;
arr[0].grade = ‘A’;
arr[0].p.age = 20;
strcpy(arr[0].p.name,”budi”);
arr[1].score = 83;
arr[1].grade = ‘b’;
arr[1].p.age = 19;
strcpy(arr[1].p.name,”chandra”);
· Memory Allocation (Dynamic)
If you need to allocate memory dynamically (in runtime), you can
use malloc in C/C++. To de-allocate you can use free.
int *px = (int *) malloc(sizeof(int));
char *pc = (char *) malloc(sizeof(char));
*px = 205;
*pc = ‘A’;
printf( “%d %c\n”, *px, *pc );
free(px);
free(pc);
· Linked List Introduction
Linked list is a data structure that consists of a sequence of data records such that each record there is a field that contains a reference to the next record in the sequence.
Example of a list whose nodes contain two fields:
an integer value and a link to the next node.
Linked list which node contain only a single link to other node is called single linked list.

Komentar
Posting Komentar