You are on page 1of 34

UNIT 1: Data Structures

UNIT

DATA STRUCTURES

In this unit we will discuss about


structuring and organizing data - a fundamental
aspect of designing and implementing computing
software. Data structures determine the logical
linkages between data elements and affect the
physical processing of data. All software
programs use data structures of some kind; many
use files as well. Data structure knowledge is
required design and develop software for either
commercial or technical applications. It also
required design and develop system software like

operating systems, database management
systems, and language compilers. Data structure
and algorithms are primary factors that determine
program performance.

The first part of this unit discusses the
different type of data structure and tells how they
are managed by computer programs. This
introductory chapter should give you an
understanding of what a data structure is and why
data structures are important in information
systems, as well as general knowledge of several
simple data structures.
3

IT 201: DATA STRUCTURES AND ALGORITHM
UNIT 1: Data Structures


PRETEST


WHAT DO YOU ALREADY KNOW?

Name: __________________________________ Date: ____________________


Course & Section: ________________________ Result: __________________

Based on your knowledge about the basics of programming concepts, select the best
answer by writing the letter/letters on the space provided for each number.

___1. Which of the following points is/are true about Algorithm?


a) It is a finite set of instructions or procedures, written in order, to solve a
certain predefined task.
b) The algorithm is not a program.
c) In programming, algorithms are implemented in the form of methods or
functions.
d) All of the above
___2. Which of the following points is/are not true about Pointers operations?
a) Define a pointer variable.
b) Assign the address of a variable to a pointer.
c) Locate the value at the address available in the pointer variable.
d) None of the above
___3. The operation of processing each element in the list is known as;
a) Merging
b) Sorting
c) Traversal
d) Inserting
___4. Two main measures for the efficiency of an algorithm are;
a) Processor and Memory
b) Complexity and Capacity
c) Time and Space
d) Data and space

4

IT 201: DATA STRUCTURES AND ALGORITHM
UNIT 1: Data Structures

___5. Which of the following is non-linear data structure?


a) Stacks
b) List
c) Strings
d) Trees
___6. Which of the following points is/are true about Linked List data structure when
it is compared with array
a) Arrays have better cache locality that can make them better in terms of
performance
b) It is easy to insert and delete elements in Linked List
c) Random access is not allowed in a typical implementation of Linked Lists
d) All of the above
___7. Which of the following data structure is linear type?
a) Graph
b) Trees
c) Binary tree
d) Stack
___8. In using pointers, what character should be used in showing the memory
address of a variables?
a) *
b) &
c) **
d) *next
___9. Which of the following points is/are true about Node?
a) To store the information and the link to the next item
b) To check for the end of the list
c) To delete items from the list
d) To add elements in the list
___10. A linked list is different from an array, because;
a) A linked list can handle more types of information than an array.
b) An array is fixed in size but a linked list is dynamically sizable.
c) An array cannot be sorted but a linked list can be sorted.
d) All of the above

5

IT 201: DATA STRUCTURES AND ALGORITHM
UNIT 1: Data Structures

___11. A linked list is implemented with an array for the storage of the
information.
a) True
b) False
___12. In addition to the information and linked list components, the linked list
must also contain what other components?
a) Sorting information about the list
b) Head and tail pointers to the first and last nodes
c) The current node that was last accessed
d) None of the above
___13. Which of the following is not a Primitive Data Structure
a) Integer
b) List
c) Boolean
d) Character
___14. Which of the following points is/are true about Data Structure?
a) Classify various data type to be stored in memory.
b) Determine what operations will be performed on a particular data.
c) The functional definition of a data structure should be independent of its
implementation since data structure is the scheme for data organization.
d) All of the above.
___15. What does ADT stand for?
a) Automatic Data Template
b) Absolute Data Type
c) Anonymous Data Template
d) Abstract Data Type

6

IT 201: DATA STRUCTURES AND ALGORITHM
UNIT 1: Data Structures

e)

LESSON 1:

INTRODUCTION TO DATA

STRUCTURES AND ALGORITHM


OBJECTIVES:


At the end of this lesson, the students will be able to:

§ Explain the concept of Data.



§ Classify the different types of Data Structure.

§ Explain the properties and characteristics of an Algorithm


7

IT 201: DATA STRUCTURES AND ALGORITHM
UNIT 1: Data Structures

Lesson 1: INTRODUCTION TO DATA STRUCTURES AND ALGORITHM

The Use of Data


Let us consider the role data plays in the events of any organization and
implementation of data structure in C++. Data represents the overall resource of the
organization, it can exist in different forms; such as numbers and characters/text on
pieces of paper, as bits and bytes stored in computer memory, or as raw facts stored
in a person's mind. They are aggregated and summarized in various meaningful ways
to form information.

A list may implement only a subset of the different operations. The outline of a listing
is extremely general, and it will be implemented during several various ways, using
the array method. And linked list methods are the two general implementation
methods in implementing a list data structure.

Data Structure
A Data Structure is a way of collecting and organizing elements or items of data. It is
an arrangement of data in a computer’s memory in such a way that it can access
quickly to the processor for the required calculations. Data Structure must be seen in
a logical concept that must address two fundamental concerns: 1) How data will be
stored. Data type is a way to classify various types of data such as integer, string, etc.
which determines the values that can be used to store the corresponding type of data,
and 2) What operations will be performed on these data. The data in the data
structures are processed by particular operations.

The particular data structure was chosen largely depends on the frequency of the
operation that needs to be performed on the data structure; traversing, searching,
insertion, deletion, sorting, and merging. The functional definition of a data structure
should be independent of its implementation since data structure is the scheme for
data organization. The functional definition of a data structure is known as Abstract
Data Type which is independent of implementation.

Algorithm

Along with data structures discussion, problem-solving is done with the help of data
structures and algorithms. An algorithm is a finite set of instructions or procedures,
written in order, to solve a certain predefined task. In programming, algorithms are
implemented in the form of methods or functions.

The algorithm is not a program, it is the main logic or solution to the problem, which
can be stated as pseudocode. Every algorithm must solve complex problems using
the following: 1) define the problem, 2) design the algorithm, and 3) solve the problem.
8

IT 201: DATA STRUCTURES AND ALGORITHM
UNIT 1: Data Structures

The following are the characteristics of a good algorithm;

1. Input and output should be well-defined,


2. All steps should be clear and definite,
3. Solutions should be effective to problems
4. It should be feasible with the available resources.
5. It should have step-by-step directions, which should be independent of any
programming code.

An algorithm is effective and fast if it takes a lesser amount of time to perform and if it
consumes less memory space. The following properties are the basis of its
performance:

1. Time Complexity It is a way to signify the amount of time needed by the


program to run to completion.
2. Space Complexity It is the amount of memory space necessary by the
algorithm, during the course of its execution. Space complexity must be taken
extremely for multi-user systems and in situations where limited memory is
available.

An algorithm generally requires space for the following components:

• Instruction Space - space required to store the executable version of the


program. This space is static but differs depending upon the number of lines of
code in the program
• Data Space - space required to store all the constants and variables value.
• Environment Space - space necessary to store the environment information
needed to restart the suspended function.

Classification of Data Structure


A data structure is a type of data that can be categorized by its organization and the
operations that are defined on it. Data structures are also known as data types.

9

IT 201: DATA STRUCTURES AND ALGORITHM
UNIT 1: Data Structures

Data Structure

Primitive Data Structure Non-Primitive Data Structure

Integer Float Pointers Boolean Characters String Array List Records Files

Linear Non-linear

Stacks Queues Linked List Trees Graph

Figure 1.1 Data Structure Organization

Data structures are divided into two types;

1. Primitive data structures

A data structure that cannot be decomposed to other data structures.


Integers, float, pointers, Booleans, and characters are under this type.
These primitive data structures are the basis for the discussion of a more
sophisticated data structure.

2. Non-primitive data structures

It is a more complicated data structure and is derived from one or more


primitive data structures. The simple data structures built from primitives
are strings, arrays, lists, records, and files.

A simple data structure can be combined in various ways to form more complex
structures. The two important kinds of more complex data structures;

1. Linear data structure

Elements are connected and accessed in sequential order by means of


logically or in sequence memory locations.

Example: stacks, queues, and linked list

2. Non-linear data structure

Data items are not arranged in sequential order.

Example: trees and graphs


10

IT 201: DATA STRUCTURES AND ALGORITHM
UNIT 1: Data Structures


ACTIVITY FOR LESSON 1

HOW DO YOU APPLY


WHAT YOU HAVE LEARNED?
Name: _______________________________ Date: _______________________
Course & Section: _____________________ Result: _____________________

Learning Check

Using your understanding on this lesson, complete the table below by supplying the
definition and by listing at least two examples of the words given on the first column.

Terminology Definition Example

Data

Data structure

Linear Data Structure

Non-linear Data Structure

Primitive Data Structure

Non-Primitive Data Structure

Be guided
1. What is meant by the term Data?
2. Be able to explain the term Data Structure.
3. Can you give the exact definition of Linear and Non-linear Data Structure?
4. Can you differentiate Primitive and Non-Primitive Data Structure?

11

IT 201: DATA STRUCTURES AND ALGORITHM
UNIT 1: Data Structures

LESSON 2:

LINKED LISTS

OBJECTIVES:
By the end of this lesson, the students will be able to:

• Identify and Understand algorithm in creating Linked List.

• Use pointers in creating program for Linked List.

• Create program for Singly Linked Lists and Doubly Linked Lists.

• Apply the Basic Operations of Linked List for Singly Linked List
and Doubly Linked List.

12

IT 201: DATA STRUCTURES AND ALGORITHM
UNIT 1: Data Structures

Lesson 2: LINKED LISTS

The Use of LISTS


A list is a collection of an ordered sequence of items. It might have properties, for
example, being sorted or unsorted, having duplicate or being unique values. The most
significant part about list structures is that data are arranged in order. Ordering means
there is a thought there is a first item, a second item, and so on. Some operations of
a list are adding, removing, and sorting.

A list may implement only a subset of the different operations. The outline of a listing
is extremely general, and it will be implemented during several various ways, using
the array method, and linked list methods are the two general implementation methods
in implementing a list data structure.

The difference between these two ways of list implementation is that arrays are stored
in computer memory consecutively and can accessed directly to any particular item
with the use of its index number and the sorted list can be searched using binary
search. Using a linked list, data are not stored consecutively in memory locations, so
an oversized block of contiguous memory is not required even for storing large
amounts of data. Each bit of information requires the storage of an additional pointer.
However, the number of additional data is expounded on a number of things within the
list already. A linked list cannot be searched using binary search as direct access to
nodes don't seem to be available.

Linked Lists Basic Concepts

A linked list is a data structure that uses pointers to connect individual list elements
and it is also made up of multiple nodes that contain the address of the next node.

Photo lifted from: tutorialspoint.com

Figure 2.1 Linked Lists

13

IT 201: DATA STRUCTURES AND ALGORITHM
UNIT 1: Data Structures

Figure 2.1 The figure represents the linked list with a pointer to the first node of the list
called Head. Each node has a link to the next node of the list. The last node has a
Null pointer, which indicates that there is no next node. Each node actually has two
parts: data contents and the pointer field. Each node is a record data structure.

To create linked in C++ we must have a clear understanding of pointer.

Pointers
Pointers are used to store addresses of a variable. Using pointers in C++, there are
three operations that the pointers do frequently; first, define a pointer variable, second,
assign the address of a variable to a pointer, and lastly, locate the value at the address
available in the pointer variable. Basically this can be done using the operator * that
returns the value of a variable located at the address specified by its operand. To
understand pointers deeply, we must know how to do the computer store variable and
its value.

int x = 30; //declaration and initialization of variable x

x Variable name
30 Variable value
00FCFB88 00FCFC7C 00FCFB70 Memory Location
Figure 2.2 Typical View of Memory Location

Figure 2.2 shows the typical view of the memory location every time we initialize a
variable. If we want to change the value of variable x, the code is simply like this:

x = 50;

Using pointer we can directly go to the memory location of “x” and change the value
of x without having to disturb “x”. This is the main point about pointer.

To declare variable pointer follow the given syntax;

int *p; // declaration of variable pointer p

To transfer the memory location of variable x to p, use the code below;

p = &x;

14

IT 201: DATA STRUCTURES AND ALGORITHM
UNIT 1: Data Structures

x p
Pointer
30 00FCFB70
00FCFB88 00FCFC7C 00FCFB70 00FCFD85
Fig. 2.3

We can now change the value of x without accessing x.

*x = 100; //changing the value of ‘x’ using pointer ‘p’


cout<<x; //display the value of ‘x’

Figure 2.4 shows the complete program for pointer operations, see Figure 2.5 for the
sample output.

1 #include <iostream>
2
3 using namespace std;
4
5 void main()
6 {
7 int x = 30; //initialization of variable x
8 int *p; // declaration of pointer variable p
9 p = &x; // store address of x in pointer variable
10
11 //display the value of variable x
12 cout<<"The value of variable x is: ";
13 cout<<x <<endl;
14 *p = 100;
15
16 //display the address stored in p pointer variable
17 cout << "Memory address stored in p variable is: ";
18 cout <<p << endl;
19
20 //locate the value at the address available in pointer
21 cout << "The value of variable *p is: ";
22 cout <<*p <<endl;
23
24 cout<<endl;
25 system(“pause”);
26 }
Figure 2.4 Sample Program using Pointers

15

IT 201: DATA STRUCTURES AND ALGORITHM
UNIT 1: Data Structures

Figure 2.5 Sample Output using Pointers in C++

To create a simple linked list in C++ use struct keyword to create a data type with a
specific characteristics which can include other data type.

Algorithms for Creating a Linked List

For example, a linked list called “Employee” and will hold name, rate as well as the
no. of hours worked (nhw) of an employee.

1. Create list Employee using struct keyword.


2. Declare name, rate, nhw and the pointer next which will point to the next node
of the list.

9 struct Employee
10 {
11 String name;
12 double rate, nhw;
13 struct Employee *next;
14 };

Figure 2.6 Code Fragment for Creating Structure

Figure 2.6 shows that the data type on the pointer next is Employee. We bind both
data item and next node reference in a struct because linked lists are known as Self
Referential, to create pointers that point to other Employee.

Algorithms for Adding a Node

Assuming Linked list Employee is created.

16

IT 201: DATA STRUCTURES AND ALGORITHM
UNIT 1: Data Structures

1. Initialize pointer head into NULL


2. Declare newEmployee with Employee as the data type
3. Add values to each field in the new Employee
newEmployee -> name = “Seth”;
newEmployee -> rate = 250.00;
newEmployee -> nhw = 44.5;
4. head = newEmployee;

Based on the algorithm written above, Figure 2.7 shows the code for adding values
for each field.

16 Employee *head = NULL;


17
18 Employee *newEmployee;
19 newEmployee = new Employee;
20 newEmployee -> name ="Seth";
21 newEmployee -> rate = 250.00;
22 newEmployee -> nhw = 44.5;
23 newEmployee -> next = NULL;
24 head = newEmployee;
25
26 newEmployee = new Employee;
27 newEmployee -> name ="Renev";
28 newEmployee -> rate = 450.00;
29 newEmployee -> nhw = 30.50;
30 newEmployee -> next = NULL;
31 head->next = newEmployee;

Figure 2.7 Sample Code for Adding Values to each Field

Using à symbol, values are added to each field; name, rate, and nhw in the new
Employee shown in Figure 2.7

Algorithms for Displaying a Node

Assuming Linked list Employee and a node is already added to the linked list.

1. Declare DisplayPtr and initialize to head


2. While(DisplayPtr)
Display name
Display rate
Display nhw
DisplayPtr = nextValue
3. Else
Exit Looping

33 Employee *DisplayPtr = head;


34
17

IT 201: DATA STRUCTURES AND ALGORITHM
UNIT 1: Data Structures

35 while(DisplayPtr)
36 {
37 cout<< DisplayPtr -> name <<" à ";
38 cout<< DisplayPtr -> rate <<" à ";
39 cout<< DisplayPtr -> nhw <<endl;
40
41 DisplayPtr = DisplayPtr -> next;
42 cout<<endl;
43 }

Figure 2.8 Sample Code for Displaying Values

DisplayPtr is a pointer that is used to move through the list.

Figure 2.9 shows the complete program for creating simple linked list in C++

1 #include <iostream>
2 #include<string>
3
4 using namespace std;
5
6 void main()
7 {
8
9 struct Employee
10 {
11 string name;
12 double rate, nhw;
13 struct Employee *next;
14 };
15
16 Employee *head = NULL;
17
18 Employee *newEmployee;
19 newEmployee = new Employee;
20 newEmployee -> name ="Seth";
21 newEmployee -> rate = 250.00;
22 newEmployee -> nhw = 44.5;
23 newEmployee -> next = NULL;
24 head = newEmployee;
25
26 newEmployee = new Employee;
27 newEmployee -> name ="Renev";
28 newEmployee -> rate = 450.00;
29 newEmployee -> nhw = 30.50;
30 newEmployee -> next = NULL;
31 head->next = newEmployee;
32
33 Employee *DisplayPtr = head;
34
35 while(DisplayPtr)
36 {
37 cout<< DisplayPtr -> name <<" à ";

18

IT 201: DATA STRUCTURES AND ALGORITHM
UNIT 1: Data Structures

38 cout<< DisplayPtr -> rate <<" à ";


39 cout<< DisplayPtr -> nhw <<endl;
40
41 DisplayPtr = DisplayPtr -> next;
42 cout<<endl;
43 }
44 system("pause");
45 }
Figure 2.9 Sample Program for Simple Linked List

Figure 2.10 Sample Output for Simple Linked List

Linked Lists Basic Operations


Having knowledge about the basic concepts of a linked list, in this part of the module,
you will learn basic operations on a linked list; traverse, insert, delete, and other
operations like; searching, sorting and merging will discuss in the next unit of this
module. Also, you will see the implementation of these operations of the linked list
using C++.

Important points to remember; head – points to the first node of the linked list and next
- pointer of the last node is NULL, if the current node is NULL we already reached the
end of the linked list.

Figure 2.11 shows the structure of the node in a linked list using a class keyword:

class classNode
{
public:
int items; //declares variable that contains data of the node
classNode *next; //variable that contains the address of the next node
};

Figure 2.11 Sample Code using Class in Linked List

19

IT 201: DATA STRUCTURES AND ALGORITHM
UNIT 1: Data Structures

Traverse a Linked List


The operation of processing each element in the list is known as traversal. The
concept of traversing list is to step through the entire list and display all elements one
by one.

struct node *data = head;


while(data != NULL)
{
cout <<data->items;
data = data->next;
}
cout<<endl;

Figure 2.12 Sample Code for Traversing Linked List

Figure 2.12, it starts with the head of the list. It accesses the content of the head node,
if the head node is not equal to NULL it will go to the next node and access the
information of the node, the loop continues until no more node found.

Insert Node to a Linked List

There are two ways that occur when inserting elements in a linked list:

• Inserting node at the beginning


• Inserting node at the end

Insertion at the beginning

To insert an element at the beginning; Figure 2.13, shows the allocation of memory
for a new node to store data, then change next of new node to point head, and
lastly change head to point to recently created node.

struct node *new_node


new_node = malloc(sizeof(struct node));
new_node->items = new_items;
new_node->next = head;
head = new_node;

Figure 2.13 Sample Code for Inserting Node at the Beginning

20

IT 201: DATA STRUCTURES AND ALGORITHM
UNIT 1: Data Structures

Insertion at the end

To insert an element at the end; Figure 2.14, shows the allocation of memory for
a new node to store data, then traverse to last node, and lastly change next of last
node to recently created node.

struct node *new_node


new_node = malloc(sizeof(struct node));
new_node->items = new_items;
new_node->next = NULL

struct node *end = head;


while (end->next != NULL)
{
end = end->next;
}
end->next = new_node;

Figure 2.14 Sample Code for Inserting Node at the End

Delete Node from a Linked List

There are two ways that occur when deleting elements from a linked list:

• Deleting node at the beginning


• Deleting node at the end

Delete from beginning

To delete node from beginning, point head to the second node use the following
code below;

head = head->next;

Delete from end

To delete an element from the end; Figure 2.15 shows the allocation of
memory for a new node to store data, then traverse to second last element,
and lastly change its next pointer to null.
.

21

IT 201: DATA STRUCTURES AND ALGORITHM
UNIT 1: Data Structures

struct node *end = head;


while(end -> next -> != NULL)
{
end = end->next;
}
end->next = NULL;

Figure 2.15 Sample Code for Inserting Node at the End

A sample program to implement basic operations in a linked list is shown in Figure


2.16 and the output from the given sample program shown in Figure 2.17.

1 #include <iostream>
2 using namespace std;
3
4 class ListOperations
5 {
6 public:
7 int items;
8 ListOperations *next;
9 };
10
11 // Function for displaying elements
12 void Display(ListOperations *data)
13 {
14 while(data != NULL)
15 {
16 cout << data->items << " ";
17 data = data->next;
18 }
19 cout<<endl;
20 }
21
22 // Function for inserting node at the beginning
23 void Add_Start(struct ListOperations **h_ref, int new_items)
24 {
25 struct ListOperations *new_node = (struct
ListOperations*)malloc(sizeof(struct ListOperations));
26 new_node->items = new_items;
27 new_node->next = *h_ref;
28 *h_ref = new_node;
29 }
30
31 // Function for inserting node at the end
32 void Add_End(struct ListOperations **h_ref, int new_items)
33 {
34 struct ListOperations *new_node = (struct ListOperations*
)malloc(sizeof(struct ListOperations));
35
36 struct ListOperations *end = *h_ref;

22

IT 201: DATA STRUCTURES AND ALGORITHM
UNIT 1: Data Structures

37 new_node->items = new_items;
38 new_node->next = NULL;
39
40 while (end->next != NULL)
41 end = end->next;
42 end->next = new_node;
43 }
44
45 // Function for deleting elements
46 void Del_Node(struct ListOperations **h_ref, int key)
47 {
48 struct ListOperations *temp = *h_ref, *prev;
49
50 if (temp != NULL && temp->items == key)
51 {
52 *h_ref = temp->next;
53 free(temp);
54 return;
55 }
56
57 // Search for the key to be deleted
58 while (temp != NULL && temp->items != key)
59 {
60 prev = temp;
61 temp = temp->next;
62 }
63
64 if (temp == NULL)
65 return;
66
67 // Delete the node
68 prev->next = temp->next;
69 free(temp);
70 }
71
72 // Main function
73 void main()
74 {
75 ListOperations *head_node = NULL;
76 ListOperations *second_node = NULL;
77 ListOperations *third_node = NULL;
78
79 head_node = new ListOperations();
80 second_node = new ListOperations();
81 third_node = new ListOperations();
82
83 head_node->items = 5;
84 head_node->next = second_node;
85
86 second_node->items = 4;
87 second_node->next = third_node;
88
89 third_node->items = 3;
90 third_node->next = NULL;
23

IT 201: DATA STRUCTURES AND ALGORITHM
UNIT 1: Data Structures

91
92 cout << "\nElements in the list: " << endl;
93 Display(head_node);
94
95 Add_Start(&head_node, 9);
96 Add_Start(&head_node, 10);
97 cout<<"\nResult of list after insertion at the start:" <<endl;
98 Display(head_node);
99
100 Add_End(&head_node, 101);
101 Add_End(&head_node, 102);
102 cout<<"\nResult of list after insertion at the end:" <<endl;
103 Display(head_node);
104
105 cout<<"\nResult of list after deleting node:" <<endl;
106 Del_Node(&head_node,101);
107 Display(head_node);
108 cout<<endl;
109
110 system("pause");
111 }

Figure 2.16 Program to Implement Basic Operations in Linked List

Figure 2.17 Sample Code for Inserting Node at the End

Types of Linked Lists

In the previous lesson, we have learned the basic concepts and operations of Linked
List. In this section, we now turn to the two common types of linked lists in C++;

24

IT 201: DATA STRUCTURES AND ALGORITHM
UNIT 1: Data Structures

1. Singly Linked List


2. Doubly Linked List

Singly Linked List

It is the most common type of linked list that contains more than one node that
linked in sequential order. Each node contains a data field that contains the
stored data and an address field that holds a reference of the next node.

Photo lifted from: programiz.com

Figure 2.18 Singly Linked List

Figure 2.18 represents the Singly Linked List, the first node of a linked list is called the
head, and the last node is called the tail. The list starts traversing from the head,
while the tail ends the list by pointing at NULL.

1 #include <iostream>
2
3 using namespace std;
4 void main() {
5
6 struct Node
7 {
8 int elements;
9 struct Node *next;
10 };
11
12 struct Node *head = NULL;
13
14 int items,inpElements;
15 cout<<"Enter number of items:";
16 cin>>items;
17
18 for(int ctr = 1 ; ctr<=items; ctr++)
19 {
20 cout<<"Enter data " <<ctr <<": ";
21 cin>>inpElements;
22
23 Node *new_node;
24 Node *nodePointer;
25 new_node = new Node;
26 new_node -> elements = inpElements;
27 new_node -> next= NULL;
25

IT 201: DATA STRUCTURES AND ALGORITHM
UNIT 1: Data Structures

28
29 if(head==NULL)
30 head=new_node;
31 else
32 {
33 nodePointer = head;
34
35 while(nodePointer->next)
36 nodePointer = nodePointer->next;
37 nodePointer->next = new_node;
38 }
39 }
40
41 cout<<"\nThe linked list are: ";
42 Node *PointerDisplay;
43 PointerDisplay=head;
44 while(PointerDisplay)
45 {
46 cout<<PointerDisplay->elements <<" ";
47 PointerDisplay = PointerDisplay->next;
48 }
49 cout<<endl;
50 system("pause");
51 }
Figure 2.19 Program Implementing Singly Linked List

Figure 2.20 Sample Output of Singly Linked List

Figure 2.21 shows that the struct Node forms the linked list node. It contains the
elements and a pointer to the next linked list node.

6 struct Node
7 {
8 int elements;
9 struct Node *next;
10 };

Figure 2.21 Sample Code for Creating Node Structure for Singly Linked List
26

IT 201: DATA STRUCTURES AND ALGORITHM
UNIT 1: Data Structures

Displaying nodes in the linked list shown in Figure 2.22.

42 Node *PointerDisplay;
43 PointerDisplay=head;
44 while(PointerDisplay)
45 {
46 cout<<PointerDisplay->elements <<" ";
47 PointerDisplay = PointerDisplay->next;
48 }

Figure 2.22 Sample Code to Display Node

Figure 2.23 shows the code for adding an elements to a linked list.

18 for(int ctr = 1 ; ctr<=items; ctr++)


19 {
20 cout<<"Enter data " <<ctr <<": ";
21 cin>>inpElements;
22
23 Node *new_node;
24 Node *nodePointer;
25 new_node = new Node;
26 new_node -> elements = inpElements;
27 new_node -> next= NULL;
28
29 if(head==NULL)
30 head=new_node;
31 else
32 {
33 nodePointer = head;
34
35 while(nodePointer->next)
36 nodePointer = nodePointer->next;
37 nodePointer->next = new_node;
38 }
39 }

Figure 2.23 Sample Code for Adding elements

Doubly Linked List

A linked list that contains additional memory to store the address of each node
points to both the next node and the previous node in the list. It shows in Figure
2. 24.

27

IT 201: DATA STRUCTURES AND ALGORITHM
UNIT 1: Data Structures

Photo lifted from: programiz.com


Figure 2.24 Doubly Linked Lists

Advantages:

• It can pass through both forward and backward ways.


• It can insert and delete node efficiently if the node to be inserted or deleted is
given.

Disadvantages:

• It needs more space as each node has additional memory for storing the
address of the previous node.
• It increases the number of modifications as the number of operations
progresses.

A sample program to implement doubly linked list is shown in Figure 2.25

1 using namespace std;


2 void main() {
3
4 //Creating structure Node
5 struct Node
6 {
7 int elements;
8 struct Node *prev; //pointer to previous elements
9 struct Node *next; //pointer to next elements
10 };
11
12 struct Node *head = NULL;
13
14 int items,inpElements;
15 cout<<"Enter number of items to input:";
16 cin>>items;
17
18 //Adding Nodes
19 for(int ctr = 1 ; ctr<=items; ctr++)
20 {
21 cout<<"Enter data " <<ctr <<": ";
22 cin>>inpElements;
23
24 Node *new_node;
25 Node *nodePointer;
26 new_node = new Node;
27 new_node -> elements = inpElements;
28 new_node -> prev = NULL;
29 new_node -> next= head;
28

IT 201: DATA STRUCTURES AND ALGORITHM
UNIT 1: Data Structures

30 if(head!=NULL)
31 head->prev=new_node;
32 head=new_node;
33 }
34
35 //Displaying contents of linked list
36 cout<<"\nThe linked list are: ";
37
38 Node *PointerDisplay;
39 PointerDisplay=head;
40
41 while(PointerDisplay != NULL)
42 {
43 cout<<PointerDisplay->elements <<" ";
44 PointerDisplay = PointerDisplay->next;
45 }
46 cout<<endl;
47 system("pause");
48 }

Figure 2.25 Program Implementing Doubly Linked List

Figure 2.26 Sample Output for Doubly Linked List

29

IT 201: DATA STRUCTURES AND ALGORITHM
UNIT 1: Data Structures


HOW DO YOU EXTEND YOUR
LEARNING?
ASSIGNMENT #1

Name: _______________________________ Date: _______________________


Course & Section: _____________________ Result: _____________________

Learning Check

In what ways can you apply your learnings about the Linked Lists? Simulate and Trace
the output of the given program below.

#include<iostream>
#include<string>

using namespace std;

void main(){
struct Book
{
string title;
double copy;
double amt;
Book *next;
};

Book *head;
head = NULL;

Book *newBook;

newBook = new Book;


newBook->title = "Data Structure and Algorithm";
newBook->copy = 5;
newBook->amt = 250.00;
newBook->next = NULL;
head= newBook;

newBook = new Book;


newBook->title = "Introduction to Computing";
newBook->copy = 10;
newBook->amt = 200.00;

30

IT 201: DATA STRUCTURES AND ALGORITHM
UNIT 1: Data Structures

newBook->next = NULL;
head -> next = newBook;

Book *displayPointer;
displayPointer = head;

while(displayPointer)
{
cout<<"\nBook Title: " <<displayPointer->title;
cout<<"\nNo. of Copies: " <<displayPointer->copy;
cout<<"\nAmount: " <<displayPointer->amt <<endl;
displayPointer = displayPointer->next;
cout<<endl;
}
system("pause");}

Write your answer here:

31

IT 201: DATA STRUCTURES AND ALGORITHM
UNIT 1: Data Structures


ACTIVITY APPLICATION FOR LESSON 2

HOW DO YOU APPLY



WHAT YOU HAVE LEARNED?

Name: _______________________________ Date: _______________________


Course & Section: _____________________ Result: _____________________

Learning Check

After our discussion about the concepts of Linked List, let us check your knowledge
by creating a code using linked list.

Be guided

1. Write down a node structure for this case:


• A teacher wants to manage each student’s master list with a computer
program. A list structure holds the following data; studID, studName,
Course, and Yr_level.

Write your answer here:

2. Create a program that will accept elements from the user, based on the created
node structure above. The number of elements depends on the no. of items
given by the user. Be able to display all the elements. Save the Project as
YourSurname_Name_Act1_List.cpp. Consider the sample output below. Your
program will be graded based on the given rubric.

32

IT 201: DATA STRUCTURES AND ALGORITHM
UNIT 1: Data Structures

Sample Output:

33

IT 201: DATA STRUCTURES AND ALGORITHM
UNIT 1: Data Structures


APPLICATION ANALYSIS FOR LESSON 2

HOW DO YOU APPLY



WHAT YOU HAVE LEARNED?

Name: _______________________________ Date: _______________________


Course & Section: _____________________ Result: _____________________

Learning Check

After our discussion about the basic operations of Linked List, let us check your
understanding by creating a program using linked lists.

Be guided:

Create a program that will call function that inserts the first node of a linked
list, insert a new link at the beginning and at the end of the list, and another function
that deletes the last list added. Suppose we have a list with the following data: 1, 3,
5;

• Calling the functions InsertStart() and InsertEnd() should give the list:
0, 1, 3, 5, 7
• Calling a function Delete() will result to this; 0, 1, 3, 5

Save the Project as YourSurname_Name_Act2_List.cpp. Your program will be graded


based on the given rubric.

34

IT 201: DATA STRUCTURES AND ALGORITHM
UNIT 1: Data Structures


GRADING RUBRICS

HOW WELL DID YOU PERFORM?


Name: _______________________________ Date: _______________________


Course & Section: _____________________ Result: _____________________

Rubric for Unit 1 – Lesson 2 Activity(50 pts.)

Program ( 9 - 10 ) (6 – 8 ) (4 - 5) (1-3) SCORE


Criteria
Program Program Program Program Program
execution executes executes with a executes with a does not
correctly with minor errors major errors execute
no syntax or (easily fixed
runtime errors. error)
Correct Program Output has Output has Output is
output displays correct minor errors multiple errors incorrect
output with no
errors
Design of Program Program Program does Output is
output displays more displays not display the poorly
than expected minimally required output designed
expected output
Design of Program is Program has Program has Program is
logic logically well slight logic significant incorrect
designed errors that do no logic errors
significantly
affect the results
Standards Program is Few Several Program is
stylistically well inappropriate inappropriate poorly
designed design choices design choices written
(i.e. poor (i.e. poor
variable names, variable names,
improper improper
indentation) indentation)
TOTAL SCORE:

35

IT 201: DATA STRUCTURES AND ALGORITHM
UNIT 1: Data Structures

REFERENCES

Goodrich, M. (2011). DATA STRUCTURE AND ALGORITHMS in C++ (2nd ed.) .


John Wiley &amp; Sons, Inc.

Drozdek A. 2012. DATA STRUCTURES AND ALGORITHMS in C++ (4th Ed.).

Cengage Learning.
Leung, C. (2017). DATA STRUCTURE AND ALGORITHMS. GitBook

36

IT 201: DATA STRUCTURES AND ALGORITHM

You might also like