ONE-WAY


one-way linked list
struct ELEMENT {
int value;
struct ELEMENT *next;
};
struct ELEMENT *head;
* a field named value will serve as storage for any useful values;
* a field named next will be used to “attach” to the next structure in the chain;
* the first structure in the chain is “attached” to a head variable, declared as follows:
- struct ELEMENT *head;
* the last structure in the chain will be attached to nothing, so we’ll assign the NULL pointer value to its next field.
struct ELEMENT {
int value;
struct ELEMENT *next;
};
struct ELEMENT *head, *ptr;
/* the one-way linked list is created here
we don't know yet how it was done
we only know that the head points to element #1 */
ptr = head;
/* ptr points to the first element now; we will move it
through all elements until we reach the end */
while(ptr != NULL) {
/* print the value stored in the element */
printf("value = %d\n", ptr -> value);
/* move ptr to the next element */
ptr = ptr -> next;
}
printf("done!");
BASIC EXAMPLE: CONSTRUCTION AND USAGE
#include <stdio.h>
#include <stdlib.h>
struct ELEMENT {
int value;
struct ELEMENT *next;
};
int main() {
struct ELEMENT *head = NULL;
struct ELEMENT *second = NULL;
struct ELEMENT *third = NULL;
// Allocate memory
head = (struct ELEMENT *)malloc(sizeof(struct ELEMENT));
second = (struct ELEMENT *)malloc(sizeof(struct ELEMENT));
third = (struct ELEMENT *)malloc(sizeof(struct ELEMENT));
// Assign values and link elements
head->value = 10;
head->next = second;
second->value = 20;
second->next = third;
third->value = 30;
third->next = NULL;
// Traverse and print
struct ELEMENT *ptr = head;
while (ptr != NULL) {
printf("value = %d\n", ptr->value);
ptr = ptr->next;
}
printf("done!\n");
// Cleanup
free(head);
free(second);
free(third);
return 0;
}
REAL-WORLD EXAMPLE: task manager storing tasks in a to-do list
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_TASK_NAME 100
struct Task {
char name[MAX_TASK_NAME];
struct Task *next;
};
int main() {
struct Task *head = NULL;
struct Task *task1 = NULL;
struct Task *task2 = NULL;
// Allocate memory
task1 = (struct Task *)malloc(sizeof(struct Task));
task2 = (struct Task *)malloc(sizeof(struct Task));
// Assign data
strcpy(task1->name, "Submit CNODP Application");
task1->next = task2;
strcpy(task2->name, "Study Windows System Programming");
task2->next = NULL;
// Set head
head = task1;
// Print task list
struct Task *ptr = head;
while (ptr != NULL) {
printf("Task: %s\n", ptr->name);
ptr = ptr->next;
}
printf("All tasks listed.\n");
// Cleanup
free(task1);
free(task2);
return 0;
}
Last updated