0% found this document useful (0 votes)
2 views

06 DS Linked Lists 1

Uploaded by

gurujeeltd989
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

06 DS Linked Lists 1

Uploaded by

gurujeeltd989
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 30

Data Structures

CT077-3-2- DSTR and Version VC1

Linked Lists
(Part 1)
Topic Structure

• Introduction to linked list


• Linked list properties
• Linked list traversal
• Linked list operation
– Create
– getSize()
– insert()

CT077-3-2-DSTR Data Structures 2


Objectives

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


• Explain linked list linear data structure
• Explain the basic properties of a linked list and
its advantages
• Be able to implement some of the basic
operations on linked lists
• Create, manipulate, and use linked list objects in
your programs

CT077-3-2-DSTR Data Structures 3


Key Terms

• Node
• Head
• Traversal

CT077-3-2-DSTR Data Structures 4


Introduction
• A collection of items can be organized and
processed in memory using a list data structure
– A list as an abstract type is a linear structure which
contains a sequence of elements (first element,
second element, last element, previous element, etc.)

• A particular example of lists is array (Array List)


– Adjacent chunks of memory, where elements
are accessed directly through integer indices

b e a d a
0 1 2 3 4 …
CT077-3-2-DSTR Data Structures 5
Introduction

• Another example of lists is Linked Lists


Why need
one?
• Array lists have advantages
– Fast random access to any element
– Easy to use and program with

• but also have disadvantages


– Array size is fixed (changing it is costly)
– Insertion of new elements and deleting existing
elements are slow operations (unless happening at
the end)
CT077-3-2-DSTR Data Structures 6
Linked Lists

• It is a series of connected nodes, where each


node is a data structure
• Every node (except last)
– Contains address of the next (following) node
• Node components
– Data: stores relevant information
– Link: stores address

Structure of a node

CT077-3-2-DSTR Data Structures 7


Linked Lists

• An arrow points to the following node’s address


– A pointer value stored in node
• Down arrow in last node indicates NULL link field,
i.e. a pointer pointing at nothing
– X mark is also used in diagrams instead of down arrow
• Head (or first) address allows access to list
elements
– Address of the first node in the list

Linked list
CT077-3-2-DSTR Data Structures 8
Linked Lists
• Example: a list containing two elements (45 and 65)
– supposing the first node is at memory location
1200, and the second node is at memory
location 1575, linked list will look like this

Linked list and values of the links

– Most of the time, we just draw arrows to indicate


pointers pointing at memory locations, since the
exact address values are not of high importance
CT077-3-2-DSTR Data Structures 9
Linked List Nodes

• Because each node of a linked list has two


components, we need to declare each node as a
class (or struct)
– Data type (or info) of a node depends on the
specific application (linked list of what?)
– The link component of each node is a pointer
class NodeType {
struct NodeType {
public:
int info;
int info;
NodeType* link;
NodeType*
};
link;
};
Or a struct can be used similarly
CT077-3-2-DSTR Data Structures 10
Linked Lists: Some Properties

• A head variable is declared as


NodeType *
head;
and it stores address of first node in the list
• For each node
– Info stores information
– Link stores address of next node

• For example, we can have the following list

CT077-3-2-DSTR Data Structures 11


Linked Lists: Some Properties

CT077-3-2-DSTR Data Structures 12


Linked Lists: Some Properties

• NodeType * current = head;


– Copies value of head into current

Value
current 2000
current->info 17
current->link 2800
current->link->info 92

CT077-3-2-DSTR Data Structures 13


Linked Lists: Some Properties

• current = current->link;
– Copies value of current->link (2800)
into current

Value
current 2800
current->info 92
current->link 1500
current->link->info 63
CT077-3-2-DSTR Data Structures 14
Linked Lists: Some Properties

Value
head->link->link 1500
head->link->link->info 63
head->link->link->link 3600
head->link->link->link->info 45
current>link->link 3600
current->link->link->info 45
current>link->link->link 0 (that is, NULL)
current>link->link->link->info Does not exist gives runtime error

CT077-3-2-DSTR Data Structures 15


Traversing a Linked List

• The basic operations of a linked list are:


– Determine the size of the list
– Insert an item in the list
– Search to determine if an item is in the list
– Accessing list elements (get and set element at index i)
– Delete an item from the list
• These operations require list traversal
– Given a pointer to the first node of the list, step through
all nodes of the list, one by one

CT077-3-2-DSTR Data Structures 16


Traversing a Linked List

• To traverse a linked list given its head pointer:

• Example, printing list’s elements:

CT077-3-2-DSTR Data Structures 17


Getting Linked List Size

• Using traversal, how to calculate the number of


elements (nodes) in the list?
current = head;
int size = 0;

while(current != NULL){
size++;
current = current->link;
}

• Is there a better way to know linked list’s size


other than scanning (traversing) the whole list
every time?
CT077-3-2-DSTR Data Structures 18
Creating a LinkedList Structure
• A class will be created to represent a Linked List object
• It encapsulates the head pointer, and possibly other data
members (will make everything public in this course to keep it
simple, but you know that proper info hiding should be used)
• It provides all the methods necessary to utilize and
manipulate a particular linked list object
class LinkedList {
public:
NodeType* head;

LinkedList();
int getSize();

...
};
CT077-3-2-DSTR Data Structures 19
Size of a LinkedList
• Create a size field (data member) encapsulated in the
LinkedList data structure (initialized to zero in constructor)
• Update the field upon insertion and deletion (+1 or -1)
class LinkedList {
public: Improve getSize() ?
NodeType* head;
This is a simple example
int size; of how a data structure
int getSize(){ and an algorithm

X
int size = 0; cooperate to implement
NodeType * current = head; efficient solutions.
while(current != NULL){
size++; We traded off extra small
current = current->link; memory (not necessarily
} always small) to gain
return size; speed in calculating the
} size of the linked list.
};
CT077-3-2-DSTR Data Structures 20
Inserting a New Element

• We can insert new elements at the beginning of


the list, at the end of it, or at given position index
class NodeType { LinkedList(){
public: this->size = 0;
int info; this->head= NULL;
NodeType* link; }
};
void insertAtBeginning(int value){
NodeType * newNode= new
class LinkedList { NodeType;
newNode->info = value;
public: newNode->link = head;
head = newNode;
NodeType* head; size++;
int size; }

// .. the other implemented methods


};
CT077-3-2-DSTR Data Structures 21
Why the New Node Should be in
the Heap?
• What happens if we change the implementation of
insert so that a new node is created in the stack?
void insertAtBeginning(int
value){
NodeType newNode; The object newNode will be
newNode.info = value; deleted from memory after
newNode.link = head; insertAtBeginning function
head = & newNode;
ends, and therefore the
size++;
head of the list will be a
}
dangling pointer.
void main(){
LinkedList list;

list.insertAtBeginning(5);

cout << list.head->info;


}
CT077-3-2-DSTR Data Structures 22
Inserting a New Element

• Draw a diagram representing what happens in


the memory by running this program:
void main(){

LinkedList l1;
LinkedList l2;

l1.insertAtBeginning(5);
l1.insertAtBeginning(9);
l1.insertAtBeginning(3);
cout << l1.getSize() << endl;

l2.insertAtBeginning(9);
l2.insertAtBeginning(7);
cout << l2.getSize() << endl;
}

CT077-3-2-DSTR Data Structures 23


Inserting a New Element at the End

• Write the code that navigates until the last node,


and then inserts the new node there
void insertAtEnd(int value){

NodeType * newNode= new


NodeType; Create and setup
newNode->info = value; the new node
newNode->link = NULL;

if (head == NULL) If the list is empty


head = newNode;
else{ The general case
NodeType * last = head; requires finding
while(last->link != NULL) the last node in
last= last->link; the list and make
last->link = newNode; its link point at
} the new node
size++;
CT077-3-2-DSTR
} Data Structures 24
Clearing a Linked List

• Sometimes you fill up a list, and want to empty it so that it


can be filled up again with new elements
• Simply assigning NULL to head and zero to size will create
a memory leak problem
void clear (){

NodeType * current = head;


while(head != NULL){
current = current->link;
delete head;
head = current;
}

size = 0;
}

CT077-3-2-DSTR Data Structures 25


Proper Cleaning of the Memory
• What should happen to the dynamically created nodes
should when the linked list object gets destructed?
• Implement the destructor to delete all the nodes when the
list object is deleted
– It can simply just call clear() method
• What is the print output of the following main program?
~LinkedList(){ void main(){
cout <<"Going to delete all "<< size if (true) {
<<" elements of the list."<< LinkedList list;
endl;
NodeType * current = head; list.insertAtBeginning(5);
while(head != NULL){
current = current->link; list.insertAtBeginning(9);
delete head; }
head = current;
} LinkedList list2;
}
CT077-3-2-DSTR Data Structures 26
Homework
• Define the classes NodeType and LinkedList in C++ project
• Provide the implementation necessary for the following code
sample to work. Confirm your correct implementation by
examining generated output
void main(){
LinkedList list;

list.insertAtBeginning(5);
list.insertAtEnd(9);
list.insertAtBeginning(3);
cout << list.getSize() << endl;
list.print();

list.insertAtEnd(11);
cout << list.getSize() << endl;
list.print();
}
CT077-3-2-DSTR Data Structures 27
Summary of Main Teaching

• Introduction to linked list


• Linked list properties
• Linked list traversal
• Linked list operation
– Create
– getSize()
– insert()

CT077-3-2-DSTR Data Structures 28


CT077-3-2-DSTR Data Structures 29
What we will cover next

• Linked list operations


– Search
– Insert
– Delete

CT077-3-2-DSTR Data Structures 30

You might also like