8/2/2019 Data Structures Using C_2
1/84
Engr. Pable, Lealou C.
8/2/2019 Data Structures Using C_2
2/84
Dynamic memory allocation the ability for aprogram to obtain more memory space atexecution time to hold new nodes, and torelease space no longer needed.
How?
1. Determine the size in bytes of a structuretype using the sizeof function,
2. Allocate a new area in memory of sizeofbytes using malloc,
3. Store a pointer to the allocated memory in avariable pointer.
8/2/2019 Data Structures Using C_2
3/84
Where: malloc() takes as an argument the number of
bytes to be allocated, and returns a pointer oftype void* (pointer to void) to the allocated
memory. Normally used with the sizeofoperator.
sizeof determines the size in bytes of thestructure for which memory is being allocated.
free() deallocates memory.
8/2/2019 Data Structures Using C_2
4/84
For example:newPtr = malloc (sizeof (struct node));
- Evaluates sizeof(struct node) to determine thesize in bytes of a structure of type struct node,
allocates a new area in memory ofsizeof(struct node) bytes, and stores a pointerto allocated memory in variable newPtr.
- Note: If no memory is available, malloc returns
a NULL pointer.To free memory dynamically allocated by thepreceding malloc call, use the statement
free(newPtr);
8/2/2019 Data Structures Using C_2
5/84
The following lines allocate an integer spacefrom the memory pointed by the pointer p.int *p;p = (int *) malloc(sizeof(int));
Allocate floating point number space for a floatpointer f.
float *f;f = (float *) malloc(sizeof(float));
8/2/2019 Data Structures Using C_2
6/84
Question:What is the output of the followinglines?
int *p, *q;
int x;p = (int *) malloc(sizeof(int));*p = 3;x = 6;
q = (int *) malloc(sizeof(int));*q=x;printf(%d %d\n, *p, *q);
p
p 3
6x
q
q 6
8/2/2019 Data Structures Using C_2
7/84
The following lines and the proceeding figure shows theeffectiveness of the free() function.
int *p, *q;
p = (int *) malloc(sizeof(int));
*p = 5;q = (int *) malloc(sizeof(int));
*q = 8;
free(p);
p = q;q = (int *) malloc(sizeof(int));
*q = 6;
printf(%d %d\n, *p, *q);
8/2/2019 Data Structures Using C_2
8/84
Self-referential structure contains a pointer memberthat points to a structure of the structure type.
Example:
struct node{
int data;struct node *nextPtr; /*points to a structure
}; of type node/*
nextPtr is referred to as a linki.e., can be used to tie
a structure of type struct node to another structure of thesame type.
Self-referential structures can be linked together to formuseful data structures such as lists, queues, stacks andtrees.
8/2/2019 Data Structures Using C_2
9/84
Data Structure the logical and mathematicalmodel of a particular organization of data.
Two types: Fixed data structures ex. Arrays, structs Dynamic data structures ex. Linked lists,
stacks, queues, binary trees.- with sizes that may grow and may shrinkduring the execution time.
8/2/2019 Data Structures Using C_2
10/84
List a collection of related data.
Two categories:
1. Linear lists
a. General listsb. Stacks
c. Queues
2. Non-linear lists
a. Trees
b. Graphs
8/2/2019 Data Structures Using C_2
11/84
8/2/2019 Data Structures Using C_2
12/84
List ImplementationsThe C language does not provide any liststructures or implementations. When weneed them, we must provide the structuresand functions for them. Traditionally, twodata types, arrays and pointers, are used fortheir implementation. The array implementation uses static structures
that are determined during the compilation orwhile the program is running.
The pointer implementation uses dynamicallyallocated structures known as linked lists.
8/2/2019 Data Structures Using C_2
13/84
Array Implementation
In an array implementation, the sequentiality ofa list is maintained by the order structure of
elements in the array (indexes). Although searching of an array for an
individual element can be very efficient,addition and deletion of elements are complex
and inefficient processes. For this reasonarrays are seldom used.
8/2/2019 Data Structures Using C_2
14/84
A general linear list is a list in which operations,such as retrievals, insertions, changes, anddeletions, can be done anywhere in the list, thatis, at the beginning, in the middle, or at the endof the list
8/2/2019 Data Structures Using C_2
15/84
Linked list an ordered collection of data in which eachelement contains the location of the nextelement or elements.- linear collection of self-referential structures,called nodes (a structure), connected bypointer links.
Two parts of a node:1. Data
- Holds the application datadata to beprocessed.2. Links
- Used to chain the data together.
8/2/2019 Data Structures Using C_2
16/84
8/2/2019 Data Structures Using C_2
17/84
LINKED LISTS NODE STRUCTURES
8/2/2019 Data Structures Using C_2
18/84
What consists a linked list?1. root node (head), allocated on the stack (anordinary C variable)
2. one or more records, allocated on the heap(by calling malloc)
Two parts:
1. link field links to the subsequent record
2. data field[s]
contain[s] the informationyou want to be stored in the linked list
8/2/2019 Data Structures Using C_2
19/84
Linked list can be maintained in sorted order byinserting each new element at the proper pointin the list.
Primary functions: Insert
Delete
isEmpty() called a predicate function itdoes not alter the list in any way; rather itdetermines if the list is empty (i.e., the pointerto the first node of the list is NULL).
8/2/2019 Data Structures Using C_2
20/84
Linked list - accessed via a pointer to the firstnode of the list; subsequent nodes are accessedvia the link pointer member stored in each node.
- by convention, the link pointer in the last nodeof the list is set to NULL to mark the end of thelist.
8/2/2019 Data Structures Using C_2
21/84
Insert a Node1. Allocate memory for the new node.2. Store the data value in the newly created
node.
3. Determine the insertion point that is, theposition within the list where the new dataare to be placed. To identify the insertionpoint, we need to know only the new nodespredecessor.
4. Point the new node to its successor.5. Point the predecessor to the new node.
8/2/2019 Data Structures Using C_2
22/84
POINTER COMBINATIONS FOR INSERT
8/2/2019 Data Structures Using C_2
23/84
INSERT NODE TO EMPTY LIST
8/2/2019 Data Structures Using C_2
24/84
INSERT NODE AT THE BEGINNING
8/2/2019 Data Structures Using C_2
25/84
INSERT NODE IN THE MIDDLE
8/2/2019 Data Structures Using C_2
26/84
INSERT NODE AT THE END
8/2/2019 Data Structures Using C_2
27/84
DELETE FIRST NODE
8/2/2019 Data Structures Using C_2
28/84
DELETE
GENERAL CASE
8/2/2019 Data Structures Using C_2
29/84
LINKED LIST TRAVERSAL
8/2/2019 Data Structures Using C_2
30/84
is a linear list in which all additions and deletionsare restricted to one end, called the top.
known as the last infirst out (LIFO) data
structure.
Graphical representation of a stack:
stackPtr
8 2 3
stackPtr
8/2/2019 Data Structures Using C_2
31/84
8/2/2019 Data Structures Using C_2
32/84
CONCEPTUAL AND PHYSICALIMPLEMENTATION
8/2/2019 Data Structures Using C_2
33/84
The stacks can be implemented by the use ofarraysand linked lists.
One way to implement the stack is to have adata structure where a variable called topkeeps the location of the elements in the stack(array)
An array is used to store the elements in the
stack
8/2/2019 Data Structures Using C_2
34/84
struct STACK{int count; /* keeps the number of elements
in the stack */
int top; /* indicates the location of the topof the stack*/
int items[STACKSIZE]; /*array to store thestack elements*/
}
8/2/2019 Data Structures Using C_2
35/84
8/2/2019 Data Structures Using C_2
36/84
initialize the stack by assigning -1 to the toppointer to indicate that the array based stack isempty (initialized) as follows:
You can write following lines in the mainprogram:
:
STACK s;
s.top = -1;:
8/2/2019 Data Structures Using C_2
37/84
Alternatively you can use the following function:
void StackInitialize(STACK *Sptr)
{Sptr->top=-1;
}
8/2/2019 Data Structures Using C_2
38/84
Pushan item onto the top of the stack (insertan item)
8/2/2019 Data Structures Using C_2
39/84
Void push (Stack *, type newItem)
Function: Adds newItem to the top of the stack.
Preconditions: Stack has been initialized and isnot full.
Postconditions: newItem is at the top of thestack.
8/2/2019 Data Structures Using C_2
40/84
void push(STACK *Sptr, int ps) /*pushes ps intostack*/
{if(Sptr->top == STACKSIZE-1){
printf("Stack is full\n");return; /*return back to main function*/}else {
Sptr->top++;Sptr->items[Sptr->top]= ps;Sptr->count++;
}
}
8/2/2019 Data Structures Using C_2
41/84
Pop an item off the top of the stack (deletean item )
8/2/2019 Data Structures Using C_2
42/84
type pop (STACK *)
Function: Removes topItem from stack and
returns with topItem Preconditions: Stack has been initialized and is
not empty.
Postconditions: Top element has been removed
from stack and the function returns with the topelement.
8/2/2019 Data Structures Using C_2
43/84
int pop(STACK *Sptr){
int pp;if(Sptr->top == -1){
printf("Stack is empty\n");
return -1; /*exit from the function*/}else {
pp = Sptr->items[Sptr->top];
Sptr->top--;Sptr->count--;return pp;
}
}
8/2/2019 Data Structures Using C_2
44/84
Data Structure To implement the linked list stack, we need two
different structures, a head node and a datanode.
Stack head
Two attributes: a top pointer and a count ofthe number of elements in the stack.
Stack data node Looks like any linked list node and contains a
link pointer to other data nodes.
8/2/2019 Data Structures Using C_2
45/84
Stack data structure
count top
data link
Stack Head Structure
Stack Node Structure
typedef struct{int count;
struct node *top;}STACK;
typedef struct node{int data;struct node *link;}STACK_NODE;
8/2/2019 Data Structures Using C_2
46/84
push inserts an element in the stack. creates a new node and places it on the top of
the stack.
Add 1 to the stack count field
To develop the insertion algorithm using alinked list, we need to analyze three differentstack conditions:
1.Insertion into an empty stack2.Insertion into a stack with data
3.Insertion into a stack when the availablememory is exhausted
8/2/2019 Data Structures Using C_2
47/84
Streams
8/2/2019 Data Structures Using C_2
48/84
pop removes a node from the top of the stack,frees the memory that was allocated to thepopped node, and returns the popped value.
Count is adjusted by subtracting 1.
If pop is successful, it returns true; if the stackis empty, it returns false.
8/2/2019 Data Structures Using C_2
49/84
POP Stack Example
8/2/2019 Data Structures Using C_2
50/84
Design for a basic stack program
8/2/2019 Data Structures Using C_2
51/84
Stacks can be used to reverse a sequence. Forexample, if a string Computers is entered bythe user the stack can be used to create anddisplay the reverse string sretupmoC as
follows.
The program simply pushesall of the charactersof the string into the stack. Then it popsand
displayuntil the stack is empty.
8/2/2019 Data Structures Using C_2
52/84
#include#include
#define STACKSIZE 50
typedef struct{
int count;int top;
char items[STACKSIZE];/*stack can containup to 50 characters*/
}STACK;void push(STACK *, char);
char pop(STACK *);
8/2/2019 Data Structures Using C_2
53/84
void push(STACK *Sptr, char ps)/*pushes psinto stack*/
{
if(Sptr->top == STACKSIZE-1){printf("Stack is full\n");
return; /*exit from the function*/
}
else {
Sptr->top++;
Sptr->count++;
Sptr->items[Sptr->top]= ps;}
}
8/2/2019 Data Structures Using C_2
54/84
char pop(STACK *Sptr){
char pp;if(Sptr->top == -1){
printf("\nStack is empty\n");exit(1);/*exit from the function*/
}
else {pp = Sptr->items[Sptr->top];Sptr->top--;Sptr->count--;
}return pp;}
int main()
8/2/2019 Data Structures Using C_2
55/84
int main(){
int i;STACK s;char p, A[20];
s.top = -1; /*indicates that the stack is empty at the beginning*/s.count=0;printf("Input the string please:\n");gets(A); /* alternatively you can use scanf("%s",A); *//*pushing the characters into the stack*/for(i=0;A[i] != '\0';i++){
p = A[i];push(&s,p);
}printf("The string in reverse order is:");/*popping and printing the string in reverse order*/while(s.count >= 0){
p=pop(&s);printf("%c",p);
}return 0;}
8/2/2019 Data Structures Using C_2
56/84
The strings where the reading from the reverse
and forward directions give the same word arecalled a palindrome. For example, the stringradar is an example for palindrome.
Among many other techniques stack can beused to determine if a string is a palindrome ornot. This is achieved by pushing all the letters ofa given word into stack and checking if the
letters popped are the same as the letter of thestring.
The following program determines if a givenstring is a palindrome or not?
8/2/2019 Data Structures Using C_2
57/84
Infix, Postfix and Prefix notations are used in manycalculators. The easiest way to implement thePostfix and Prefix operations is to use stack. Infixand prefix notations can be converted to postfix
notation using stack.The reason why postfix notation is preferred is thatyou dont need any parenthesis and there is noprescience problem.
8/2/2019 Data Structures Using C_2
58/84
In Postfixnotation the expression is scannedfrom left to right. When a number is seen it is
pushed onto the stack; when an operator isseen the operator is applied to the two numberspopped from the stack and the result is pushedback to the stack.
Ex: 6 5 2 3 + 8 * + 3 + * is evaluated as follows:
http://c/Documents%20and%20Settings/Administrator/Desktop/PostfixCalculations.ppthttp://c/Documents%20and%20Settings/Administrator/Desktop/PostfixCalculations.ppt8/2/2019 Data Structures Using C_2
59/84
Scan the Infix expression left to right If the character x is an operand
Output the character into the PostfixExpression
If the character xis a left or right parenthesis If the character is ( Push it into the stack
if the characteris ) Repeatedly pop and output all the
operators/characters until ( is popped fromthe stack.
8/2/2019 Data Structures Using C_2
60/84
If the character x is a is a regular operator Step 1: Check the character y currently at the
top of the stack. Step 2: If Stack is empty or y=( or y is an
operator of lower precedencethan x, thenpush x into stack. Step 3: If y is an operator of higher or equal
precedence than x, then pop and output yand push x into the stack.
When all characters in infix expression areprocessed repeatedly pop the character(s) fromthe stack and output them until the stack is empty.
8/2/2019 Data Structures Using C_2
61/84
Infix Expression
( a + b - c ) * d ( e + f )
Postfix Expression
8/2/2019 Data Structures Using C_2
62/84
A queue is a linear list in which data can beinserted only at one end, called the rear, and
deleted from the other end, called thefront.Note
It is a first infirst out
(FIFO) restricted data structure.
8/2/2019 Data Structures Using C_2
63/84
Queue Concept
8/2/2019 Data Structures Using C_2
64/84
Queue Operations
1. Enqueue
2. Dequeue
Enqueue inserts an element at the rear of thequeue.
Dequeue deletes an element at the front of thequeue.
8/2/2019 Data Structures Using C_2
65/84
items[MAXQUEUE-1]
. .
. .
. .
items[2] C
items[1] B
items[0] A
8/2/2019 Data Structures Using C_2
66/84
# define MAXQUEUE 50 /* size of the queue items*/
typedef struct {
int front;
int rear;
int items[MAXQUEUE];
}QUEUE;
8/2/2019 Data Structures Using C_2
67/84
Initializethe queue Insertto the rear of the queue
Remove(Delete) from the front of the
queue Is the Queue Empty
Is the Queue Full
What is the size of the Queue
8/2/2019 Data Structures Using C_2
68/84
The queue is initialized by having the rearset to -1, and frontsetto 0. Let us assume that maximum number of the element wehave in a queue is MAXQUEUE elements as shown below.
items[MAXQUEUE-1]
. .
. .
.items[1]
items[0] front=0
rear=-1
8/2/2019 Data Structures Using C_2
69/84
an item (A) is insertedat the Rearof thequeue
items[MAXQUEUE-1]
. .
. .
items[3]
items[2]items[1]
items[0] A Front=0,Rear=0
8/2/2019 Data Structures Using C_2
70/84
A new item (B) is insertedat the Rearof thequeue
items[MAXQUEUE-1]
. .
. .
items[3]
items[2]items[1] B Rear=1
items[0] A Front=0
8/2/2019 Data Structures Using C_2
71/84
A new item (C) is insertedat the Rearof thequeue
items[MAXQUEUE-1]
. .
. .
items[3]
items[2] C Rear=2
items[1] B
items[0] A Front=0
8/2/2019 Data Structures Using C_2
72/84
A new item (D) is insertedat the Rearof thequeue
items[MAXQUEUE-1]
. .
. .
items[3] D Rear=3
items[2] C
items[1] B
items[0] A Front=0
8/2/2019 Data Structures Using C_2
73/84
an item (A) is removed (deleted) from theFrontof the queue
items[MAXQUEUE-1]
. .
. .
items[3] D Rear=3
items[2] Citems[1] B Front=1
items[0] A
8/2/2019 Data Structures Using C_2
74/84
Removetwo items from the front of thequeue.
items[MAXQUEUE-1]
. .
. .
items[3] D Rear=3
items[2] C Front=2
items[1] B
items[0] A
8/2/2019 Data Structures Using C_2
75/84
Assume thatthe rear= MAXQUEUE-1
What happens if we want to insert a new item into thequeue?
items[MAXQUEUE-1] X rear=MAXQUEUE-1
. .
. .
items[3] D front=3
items[2] C
items[1] B
items[0] A
8/2/2019 Data Structures Using C_2
76/84
What happens if we want to insert a new item Finto the queue?
Although there is some empty space, the
queue is full.
One of the methods to overcome this problemis to shift all the items to occupy the locationof deleted item.
8/2/2019 Data Structures Using C_2
77/84
Since all the items in the queue are required toshift when an item is deleted, this method is notpreferred.
The other method is circular queue.
When rear = MAXQUEUE-1, the next element isentered at items[0] in case that spot is free.
8/2/2019 Data Structures Using C_2
78/84
#define MAXQUEUE 10 /* size of the queue items*/typedef struct {
int front;int rear;int items[MAXQUEUE];
}QUEUE;
QUEUE q;q.front = MAXQUEUE-1;
q.rear= MAXQUEUE-1;
8/2/2019 Data Structures Using C_2
79/84
void insert(QUEUE *qptr, char x){if(qptr->rear == MAXQUEUE-1)
qptr->rear=0;else
qptr->rear++;/* or qptr->rear=(qptr->rear+1)%MAXQUEUE) */if(qptr->rear == qptr->front){
printf("Queue overflow");exit(1);
}
qptr->items[qptr->rear]=x;}
8/2/2019 Data Structures Using C_2
80/84
char remove(struct queue *qptr){if(qptr->front == qptr->rear){
printf("Queue underflow");exit(1);
}if(qptr->front == MAXQUEUE-1)
qptr->front=0;else
qptr->front++;return qptr->items[qptr->front];
}
8/2/2019 Data Structures Using C_2
81/84
Conceptual and Physical QueueImplementations
8/2/2019 Data Structures Using C_2
82/84
Queue Data Structure
8/2/2019 Data Structures Using C_2
83/84
Enqueue Examples
8/2/2019 Data Structures Using C_2
84/84
Dequeue Examples