Lec08-Struct Union Linked List
Lec08-Struct Union Linked List
Cuong Do
▪ Struct (Cont’d)
▪ Union
▪ Linked-list
struct Student
{
char name[50];
char Major;
int year;
};
// pass by value
void printStudent(struct Student var) {
// pass by reference
void changeStudent(struct Student* var)
{
var->year = 21;
var->major = ‘EE';
}
int main(){
struct Student student1 = {“Elon Musk", ‘ME’, 22}; // initialising the object
// passing by value
printStudent(student1);
// passing by reference Output:
changeStudent(&student1); Student name : Elon Musk
Student section : ME
return 0; Student class : 22
}
motor m;
You must write
struct motor m;
motor *p; struct motor *p;
… /* In another file */
struct _item {
char *info;
Item *nextItem;
};
#include <stdio.h>
struct Area
{
//Anonymous union
union
{
int radius;
int height;
};
};
int main()
{
struct Area r, h;
r.radius = 15;
use 2 separate struct
h.height = 10;
int area;
return 0;
}
▪ a = 20;
▪ b = 10;
#include <stdio.h>
#include <conio.h>
int main() {
int a=10, b=20;
return 0;
}
struct listItem {
type payload;
struct listItem *next;
}; payload
next
payload
next
payload
payload next
next
Linked List (continued)
▪Items of list are usually same type
▪ Generally obtained from malloc()
▪Each item points to next item
▪Last item points to null
▪Need “head” to point to first item!
struct listItem {
type payload;
struct listItem *next;
};
struct listItem *head;
payload
payload next
next
payload
payload
next
next
Adding an Item to a List
payload
next
payload
payload
next
next
payload
payload
next
next
Adding an Item to a List
payload
next payload
payload
next
next
payload
payload
next
next
Adding an Item to a List
payload
next payload
payload
next
next
payload
payload
next
next
Adding an Item to a List
Question: What to do if we cannot
guarantee that p and q are non-NULL?
listItem *addAfter(listItem *p, listItem *q){
q -> next = p -> next;
p -> next = q;
return p;
}
payload
next payload
payload
next
next
payload
payload
next
next
Adding an Item to a List (continued)
payload
next
payload
payload
next
next
payload
payload
next
next
What about Adding an Item before another Item?
▪ Answer:–
▪ Need to search list from beginning to find previous item
▪ Add new item after previous item
struct listItem {
type payload;
listItem *prev;
listItem *next;
};
struct listItem *head, *tail;
payload payload
prev next prev next payload
payload prev next
prev next
Other Kinds of List Structures
▪Queue — FIFO (First In, First Out)
▪ Items added at end
▪ Items removed from beginning
▪Stack — LIFO (Last In, First Out)
▪ Items added at beginning, removed from beginning
▪Circular list
▪ Last item points to first item
▪ Head may point to first or last item
▪ Items added to end, removed from beginning
payload
payload
next
next
payload
payload
next
next