Professional Documents
Culture Documents
9. Structures in C
struct Point
int x, y;
Or
struct Point
int x, y;
};
int main()
Structure members cannot be initialized with declaration. For example the following C
program fails in compilation.
struct Point
};
struct Point
{
int x, y;
};
int main()
{
// Create an array of structures
struct Point arr[10];
}
struct Point
{
int x, y;
};
int main()
{
struct Point P1;
A linked list is an ordered collection of nodes, each of which contains some data,
connected using pointers. Each node is actually a struct variable, which contains an ID,
the additional data of the object and a pointer variable that points to the next node. For
example, the next structure is defined for a list of cars in a car lot.
struct carType
{
int vehicleID;
char make[20];
char model[20];
int year;
int mileage;
double cost;
Car *next; // ptr to next car in list
};
See more on point 12.
Queue is a FIFO (First-In, First-Out) list, a list-like structure that provides restricted
access to its elements: elements may only be inserted at the back and removed from the
front. Similarly to stacks, queues are less flexible than lists.
c. operations on queue
Last (new)
First
element
element
1. Allocate a new node and hold the pointer to it in a variable. Return from the insert
function now signaling an error if the new node cannot be allocated.
1. Allocate a new node and hold the pointer to it in a variable. Return from the insert
function now signaling an error if the new node cannot be allocated.
2. Store the information in the newly created node.
3. Make the newly created node point to null.
4. Make the old rear node point the newly created node.
5. Make rear point to the newly created node.
Checking for an empty queue checks to see if either the front or the rear points to null.
Checking for a full queue should always return false.
Delete an element:
1. If the queue is empty, return a flag indicating that removal could not be performed.
The Lee algorithm is one possible solution for maze routing problems. It always gives an
optimal solution, if one exists, but is slow and requires large memory for dense layout.
3. Remove the position you are on from the queue and continue to the next element.
Using the example of a maze solving algorithm, a depth-first approach will try every
possible path one by one until it either reaches a dead end or the finish and returns the
result. However, the path it returns might not be the most efficient, but simply the first
complete path to the finish that the algorithm was able to find.
A breadth-first search will instead go out to each open space adjacent to the starting
point, then look for other possible open spaces. It will keep doing this, going out layer by
layer and trying each possible path in tandem, until it finds the finish point. Since you're
trying each path at the same time, you can be sure that the first complete path from
start to finish is also the shortest.
C++ has the queue already implemented in the <queue> library, but if you are using
something else you are welcome to implement your own version of queue.
C++ code:
int dl[] = {-1, 0, 1, 0}; // these arrays will help you travel in the 4 directions more easily
int dc[] = {0, 1, 0, -1};
void lee()
{
int x, y, xx, yy;
while(!X.empty()) // while there are still positions in the queue
{
x = X.front(); // set the current position
y = Y.front();
for(int i = 0; i < 4; i++)
{
xx = x + dl[i]; // travel in an adiacent cell from the current position
yy = y + dc[i];
if('position is valid') //here you should insert whatever conditions should apply for
your position (xx, yy)
{
X.push(xx); // add the position to the queue
Y.push(yy);
mat[xx][yy] = -1; // you usually mark that you have been to this position in the
matrix
}
X.pop(); // eliminate the first position, as you have no more use for it
Y.pop();
}
}
11. Dynamic memory allocation in C. Linear data structures: stack
Stack is a LIFO (Last-In, First-Out) list, a list-like structure in which elements may be
inserted or removed from only one end (last-in, first-out). Stacks are less flexible than
lists, but are easier to implement, and more efficient (for those operations they can do).
Given a stack, the accessible element of the stack is called the top element.
Elements are not said to be inserted; they are pushed onto the stack.
When an element (the last one) is removed, an element is said to be popped from the
stack.
b. Stack structure
c. Stack operations
Given two numbers N1 and N2 represented by two stacks, such that their most
significant digits are present at the bottom of the stack, the task is to calculate and
return the sum of the two numbers in the form of a stack.
2. Initialize variables rem and sum to store the carry generated and the sum of top
elements respectively.
3. Keep popping the top elements of both the stacks and push the sum % 10 to res and
update rem as sum/10.
4. Repeat the above step until the stacks are empty. If rem is greater than 0,
insert rem into the stack.
5. Reverse the res stack so that the most significant digit present at the bottom of
the res stack.
Example:
A linked list is an ordered collection of nodes, each of which contains some data,
connected using pointers.
Ordered List:
Every node has an ID. When adding a new node in the list, we need to find firstly the
idea of the next node from the one we want to add and do the operation. This way
the list remains ordered.
When deleting the node, you search it by it’s ID and then extract it from the least,
before destroying it, otherwise you may lose half of the list.
Unordered List:
Doesn’t differ any much from what a queue or a stack is. The nodes are added either
to the front or to the back of the list.
When deleted, you can either erase the first node, the last one or find the one with
the information you want to delete from the list, extract it and erase it from the
memory.
Properties:
Each element in the list points to the next element. That’s how they hold together.
Imagine a bunch of children, which have names and are holding with the left hand the
right shoulder of the next child. The information are their names, the pointer to the next
child are their left hand. If you break one of the connections, you lose al the nodes (kids)
after the broken connection. For example, if you have the list “ABCDEFG” and you break
the connection between “C” and “D”, you lose the sublist “DEFG”.
c. List operations
Step 1: Create the new node, pointing to null, and insert the information in it.
Step 2: Find in the list the node A before which you want to add the new node, and
the node B, which is after A. Generate an error if you don’t find the points.
Step 3: Point the *next pointer of your new node to B.
Step 4: Point the *next pointer of A to your new node.
Adding a node at the top of the list:
Step 1: Create the new node, pointing to null, and insert the information in it.
Step 2: Point the *next pointer of your new node to the top node.
Step 3: Actualize the top node, which is your new variable.
Adding a node at the bottom of the list:
Step 1: Create the new node, pointing to null, and insert the information in it.
Step 2: Find the bottom node, knowing that it’s pointer *next points to null.
Step 3: Point the *next pointer of the bottom node to your new node.
Erasing a node between 2 nodes:
Step 1: Find in the list the node before the one with the information you want to
erase. If you can’t find it, generate an error message.
Step 2: Point the *next pointer of the node to the *next pointer of the next node of
the one you want to delete.
Step 3: Point the *next pointer of the node you want to delete to null.
Step 4: Erase the node from the memory.
Step 1: Actualize the TOP node, which is the next node of the one you want to
delete.
Step 2: Point the *next pointer of the node you want to delete to null. Erase the
node from memory.
Deleting a node at the bottom of the list:
Step 1: Find the bottom node, knowing that it’s pointer *next points to null.
Step 2: Point the *next pointer of the previous node to null. Erase your node from
the memory.
Couldn’t find anything on the internet. But, the operation is simple. Read the elements
of the string, transform them to nodes and add to the list in ordered form (only if the
order of the character in the string does not actually matter, otherwise, just add the
nodes to the top), search through the list by ID and that’s all.
Practice:
{
int temp = 0;
for (int i = 0; i < str.length(); i++) {
// Since ASCII value of character from '0'
// to '9' are contiguous. So if we subtract
// '0' from ASCII value of a digit, we get
// the integer value of the digit.
temp = temp * 10 + (str[i] - '0');
// ASCII of number x – ASCII of 0 = number x
}
return temp;
}
16. GCD (Greatest Common Divisor) between 2 numbers. Euclid’s algorithm
Step 2: a mod b = R
Step 5: GCD = b
Step 6: Finish
function gcd(a, b) {
var R;
while ((a % b) > 0) {
R = a % b;
a = b;
b = R;
}
return b;
}
if (n == 0 || n == 1 || n == 2) {
isPrime = false;
}
else {
for (i = 2; i <= n / 2; ++i) {
if (n % i == 0) {
isPrime = false;
break;
}
}
}
if (isPrime)
cout << n << " is a prime number";
else
cout << n << " is not a prime number";
float sqRoot(float N) {
x = (x + y)/2;
y = N/x;
}
return x;
Let d be the digit and N the number. d = N mod 10. N = N div 10. Write d, repeat until N=0.
while (number > 0)
{
int digit = number % 10;
number /= 10;
//print digit
}
1. X is the number in base 10, b is the new base, i=0 and S is an empty string. While x>0
repeat steps 2 and 3;
2. R is the reminder of X/b. Add to S the (R+’0’).
3. Increase i by one, divide X by b.
4. Result is 0. Iterative, form the last element of S down to the first one, multiply the result
to 10 and add the number from string to it. That’s the answer.
int From10toB (int number, int b)
String S;
while (x>0) {
rem=x % b;
S[i]=rem + ’0’;
i++;
x \= b;
};
int result=0;
return result;