C data structures
Created By: chatGPT
In C programming, a data structure is a way of organizing and storing data that enables efficient access and modification. C provides several built-in data structures, but you can also create your own. Here are some of the most common data structures in C:
Arrays: An array is a collection of items stored at contiguous memory locations. It is defined by specifying the type of the elements and the number of elements in the array.
int numbers[10]; // An array of 10 integers
Structures: A structure in C allows you to group different types of data together. You can define a structure using the
struct
keyword.struct Person {
char name[50];
int age;
};
Unions: A union is similar to a structure but allows you to store different data types in the same memory location, effectively allowing multiple data types to be stored in a single variable.
union Data {
int intValue;
float floatValue;
};
Linked Lists: A linked list is a collection of nodes where each node contains data and a pointer to the next node in the sequence. It allows for efficient insertion and deletion of elements.
struct Node {
int data;
struct Node* next;
};
Stacks: A stack is a Last In First Out (LIFO) data structure. It allows operations such as push (insert an element) and pop (remove the top element).
struct Stack {
int top;
unsigned capacity;
int* array;
};
Queues: A queue is a First In First Out (FIFO) data structure that allows elements to be added at the back and removed from the front.
struct Queue {
int front, rear, size;
unsigned capacity;
int* array;
};
Graphs: A graph data structure consists of nodes (vertices) connected by edges. It's often used to represent networks, such as social networks or computer networks.
struct Graph {
int numVertices;
struct Node** adjLists;
};
Trees: A tree is a hierarchical data structure with a root value and subtrees of children, represented as a set of linked nodes. They are commonly used for hierarchical data representation.
Choosing the appropriate data structure can greatly affect the efficiency of your program. Always consider the trade-offs between memory usage and operation speed when working with different data structures.struct TreeNode {
int data;
struct TreeNode* left;
struct TreeNode* right;
};