Linked lists are a linear data structure where each element, called a node, contains information and a pointer to the next node. Each node has two parts - the data and a pointer to the next node. Nodes can be dynamically allocated and linked together using pointers to form a linked list. Basic operations on linked lists include inserting and deleting nodes from the front and back of the list, as well as searching the list for a given element.
In computer science, a linked list is a linear collection of data elements, in which linear order is not given by their physical placement in memory. Instead, each element points to the next
In computer science, a linked list is a linear collection of data elements, in which linear order is not given by their physical placement in memory. Instead, each element points to the next
Homework 05 - Linked Lists (C++)(1) Implement the concepts of a un.pdfezzi97
Homework 05 - Linked Lists (C++)
(1) Implement the concepts of a union, and difference as defined noted in Chapter 1 questions 6,
and 8 using a linked list. You should not use arrays, dynamic arrays or the STL vector or STL
list classes.
You will be linking a series of nodes together to implement a single linked list class. Define a
Node as a struct that holds a character (like they did in the book) and a pointer to another Node:
struct Node {
char data;
Node* next;
};
Then define a LinkedList class which has (at a minimum) these member functions:
LinkedList();
~LinkedList();
bool insertAtFront();
bool insertBeforePosition(int index);
bool insertAtBack();
bool deleteAtFront();
bool deleteBeforePosition(int index);
bool deleteAtBack();
Implement each of these functions to provide the correct functionality. These functions return
true if successful in inserting or deleting, otherwise they return false (indicating the operation
was not successful).
Finally, create an overloaded + operator to handle the Union of two linked lists and an
overloaded - operator to handle the Difference of two linked lists.
Because we are dealing with pointers you should have both a LinkedList Constructor and
Destructor. Remember that you do not directly call a Constructor or Destructor Function. The
Destructor is automatically called when the variable loses scope or the program ends.
Remember, that we are dealing with not just one dynamically allocated Node (with the new
operator), but many, so you will have to start at the head of the list and go until the Node points
to nullptr. Then keep deleting the previous Node pointer until there are no Nodes left to delete.
(2) To verify your set class, write a main function that takes two lines of characters from the
input file input.txt and store each line of characters into two separate linked lists. Then using
these two lists, perform the Union and set Difference of the characters from the file, and print the
results to the console.
(3) Please also complete an asymptotic (Big O) analysis of your insertAtFront() and
insertAtBack() member functions. Place this in a file called analysis.txt.
Solution
Here is the complete code for your question. Please do rate the aswer if you are happy with
program. Please read comments in the program. Also pay special attention to comments in + and
- operators. You WILL NEED to comment out if condition in + if you want all elements in both
lists irrespective of if they duplicates or no. For now implemented to have true behaviour of no
duplicates in union.
check the functions by creating some lists and playing around different fucntions like its done in
main and commented out.
As far as complexity:
for insertAtFront() its O(1) since it does not depend on the size of the list. It just replaces the start
of the list. Hence it is O(1) and independent of the size of list.
for insertAtBack(), its O(n) since it depends on the number of elements in the list. It should
traverse till end of list and .
C++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdfcallawaycorb73779
C++ problem
Part 1: Recursive Print (40 pts)
Please write the recursive List reverse print function, whose iterative version we wrote in class.
Below are the function signatures for the functions you are going to need:
public:
/**Additional Operations*/
void print_reverse();
//Wrapper function that calls the reverse helper function to print a list in reverse
//prints nothing if the List is empty
private:
void reverse(Nodeptr node);
//Helper function for the public printReverse() function.
//Recursively prints the data in a List in reverse.
Why do we need the private helper function here?
Since we are going to be reversing our list node by node, in a recursive fashion, we want to pass
a one node at a time to our reverse function.
However, since our nodes are private, we cannot access them if we call the function inside of
main.
Add these function signatures to your List.h file along with your other function prototypes inside
the class definition.
Make sure that you place the reverse function inside the private portion of your List class
definition and the print_reverse function prototype to the public portion of your List class
definition.
Now, implement these two functions inside of List.h, under your section for additional
operations.
Important: Test each function carefully inside of your ListTest.cpp to make sure that it is
working properly.
Part 2: Adding an Index to Your List Nodes (20 pts)
Next, you will add the following functions to your List.h
/**Accessor Functions*/
int get_index();
//Indicates the index of the Node where the iterator is currently pointing
//Nodes are numbered from 1 to length of the list
//Pre: length != 0
//Pre: !off_end()
...
int List::get_index()
{
//Implement the function here
}
/**Manipulation Procedures*/
void scroll_to_index(int index);
//Moves the iterator to the node whose index is specified by the user
//Pre: length != 0
...
void scroll_to_index(int index)
{
//Implement function here
}
Part 3: Implementing Search as Part of Your List (40 pts)
Now, we are going to add two search functions to our List so that we can search for elements in
our List.
The first of these functions is going to be a simple linear search function.
You will need to add the following function prototype and function definition to your List.h:
/**Additional Operations*/
int linear_search(listitem item);
//Searchs the list, element by element, from the start of the List to the end of the List
//Returns the index of the element, if it is found in the List
//Returns -1 if the element is not in the List
//Pre: length != 0
...
int List::linear_search(listitem item)
{
//Implement the function here
}
You are also going to add a function to perform recursive binary search on your List.
You will need to add the following function prototype and function definition to your List.h:
int binary_search(int low, int high, listitem item);
//Recursively searchs the list by dividing the search space in half
//Returns the index of the element, if it is fo.
C++ Please test your program before you submit the answer.pdfaashisha5
C++. Please, test your program before you submit the answer.
Background:
Circular Linked List: A circular linked list is a linked list where a non-empty list has no null pointers.
Unless empty, each node has a pointer to the next node, and the last node points back to the first
node.
Assigment:
Write a cpp program that will serve the purpose of a test driver for previously written CLinkedList.h
file. Your program will:
1) Create a choice menu and prompt the user for input. Must be case insensitive!
2) Read the input and call for functions outside of main, in order to perform operations chosen by
the user. These functions involve: Inserting Interger, Removing Interger, Forward Print and
Backward Print.
Requirements and Notes:
1. Forwards Print does not require a subfunction in order to produce output. All the other
operations must call corresponding subfunctions.
2. Nodes of the circular list must be arranged in ascending order.
3. User Input must be processed case insensitive, and implemented using the loop.
4. Document your code completely.
5. CLinkedList.h file contains 3 classes.
- Circular linked lists class with following member functions: constructor, copy constructor,
destructor, assignment operator, insert and remove.
- Node class included in the file header.
- A list iterator class provides a public interface to the list. The pointer points at nodes in the linked
list. Its member functions are as follows:
Constructor: Assigns the linked list data member to the parameter, a reference to a circular linked
list.
begin() sets the iterator to the first node of the linked list (or NULL if the list is empty)
isEmpty() returns whether or not the wrapped linked list is empty
isFirstNode() returns whether the present node is the first node of the linked list
isLastNode() returns whether the present node is the last node of the linked list
operator*() returns the data of the node currently pointed at. (You need 2)
operator++() pre-increment operator advances the pointer to the next node in the list, if there is
one
operator++(int) post-increment operator advances the pointer to the next node in the list, if there
is one
6. Insert function must give feedback where it says the position of where the int was inserted for
example: "Inserting 25 in the middle."
7. Remove function must give either one of these types of feedback:
- "Removing 25" if the int given by the user was found in the list
-"Cannot find 25" if it was not. The program will then move the user back to the choice menu.
Files:
// File: Node.h
// Singly-linked list node definition/implementation (also good for circular)
#ifndef NODE_H
#define NODE_H
// Need to prototype template classes if they are to be friends
template <typename eltType> class CLinkedList;
template <typename eltType> class CListItr;
template <typename eltType> class Node
{ private:
Node(eltType info, Node* link = NULL ) :
data(info), next(link)
{};
eltType data;
Node *next;
friend class CLinkedList<eltType>;
friend c.
Homework 05 - Linked Lists (C++)(1) Implement the concepts of a un.pdfezzi97
Homework 05 - Linked Lists (C++)
(1) Implement the concepts of a union, and difference as defined noted in Chapter 1 questions 6,
and 8 using a linked list. You should not use arrays, dynamic arrays or the STL vector or STL
list classes.
You will be linking a series of nodes together to implement a single linked list class. Define a
Node as a struct that holds a character (like they did in the book) and a pointer to another Node:
struct Node {
char data;
Node* next;
};
Then define a LinkedList class which has (at a minimum) these member functions:
LinkedList();
~LinkedList();
bool insertAtFront();
bool insertBeforePosition(int index);
bool insertAtBack();
bool deleteAtFront();
bool deleteBeforePosition(int index);
bool deleteAtBack();
Implement each of these functions to provide the correct functionality. These functions return
true if successful in inserting or deleting, otherwise they return false (indicating the operation
was not successful).
Finally, create an overloaded + operator to handle the Union of two linked lists and an
overloaded - operator to handle the Difference of two linked lists.
Because we are dealing with pointers you should have both a LinkedList Constructor and
Destructor. Remember that you do not directly call a Constructor or Destructor Function. The
Destructor is automatically called when the variable loses scope or the program ends.
Remember, that we are dealing with not just one dynamically allocated Node (with the new
operator), but many, so you will have to start at the head of the list and go until the Node points
to nullptr. Then keep deleting the previous Node pointer until there are no Nodes left to delete.
(2) To verify your set class, write a main function that takes two lines of characters from the
input file input.txt and store each line of characters into two separate linked lists. Then using
these two lists, perform the Union and set Difference of the characters from the file, and print the
results to the console.
(3) Please also complete an asymptotic (Big O) analysis of your insertAtFront() and
insertAtBack() member functions. Place this in a file called analysis.txt.
Solution
Here is the complete code for your question. Please do rate the aswer if you are happy with
program. Please read comments in the program. Also pay special attention to comments in + and
- operators. You WILL NEED to comment out if condition in + if you want all elements in both
lists irrespective of if they duplicates or no. For now implemented to have true behaviour of no
duplicates in union.
check the functions by creating some lists and playing around different fucntions like its done in
main and commented out.
As far as complexity:
for insertAtFront() its O(1) since it does not depend on the size of the list. It just replaces the start
of the list. Hence it is O(1) and independent of the size of list.
for insertAtBack(), its O(n) since it depends on the number of elements in the list. It should
traverse till end of list and .
C++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdfcallawaycorb73779
C++ problem
Part 1: Recursive Print (40 pts)
Please write the recursive List reverse print function, whose iterative version we wrote in class.
Below are the function signatures for the functions you are going to need:
public:
/**Additional Operations*/
void print_reverse();
//Wrapper function that calls the reverse helper function to print a list in reverse
//prints nothing if the List is empty
private:
void reverse(Nodeptr node);
//Helper function for the public printReverse() function.
//Recursively prints the data in a List in reverse.
Why do we need the private helper function here?
Since we are going to be reversing our list node by node, in a recursive fashion, we want to pass
a one node at a time to our reverse function.
However, since our nodes are private, we cannot access them if we call the function inside of
main.
Add these function signatures to your List.h file along with your other function prototypes inside
the class definition.
Make sure that you place the reverse function inside the private portion of your List class
definition and the print_reverse function prototype to the public portion of your List class
definition.
Now, implement these two functions inside of List.h, under your section for additional
operations.
Important: Test each function carefully inside of your ListTest.cpp to make sure that it is
working properly.
Part 2: Adding an Index to Your List Nodes (20 pts)
Next, you will add the following functions to your List.h
/**Accessor Functions*/
int get_index();
//Indicates the index of the Node where the iterator is currently pointing
//Nodes are numbered from 1 to length of the list
//Pre: length != 0
//Pre: !off_end()
...
int List::get_index()
{
//Implement the function here
}
/**Manipulation Procedures*/
void scroll_to_index(int index);
//Moves the iterator to the node whose index is specified by the user
//Pre: length != 0
...
void scroll_to_index(int index)
{
//Implement function here
}
Part 3: Implementing Search as Part of Your List (40 pts)
Now, we are going to add two search functions to our List so that we can search for elements in
our List.
The first of these functions is going to be a simple linear search function.
You will need to add the following function prototype and function definition to your List.h:
/**Additional Operations*/
int linear_search(listitem item);
//Searchs the list, element by element, from the start of the List to the end of the List
//Returns the index of the element, if it is found in the List
//Returns -1 if the element is not in the List
//Pre: length != 0
...
int List::linear_search(listitem item)
{
//Implement the function here
}
You are also going to add a function to perform recursive binary search on your List.
You will need to add the following function prototype and function definition to your List.h:
int binary_search(int low, int high, listitem item);
//Recursively searchs the list by dividing the search space in half
//Returns the index of the element, if it is fo.
C++ Please test your program before you submit the answer.pdfaashisha5
C++. Please, test your program before you submit the answer.
Background:
Circular Linked List: A circular linked list is a linked list where a non-empty list has no null pointers.
Unless empty, each node has a pointer to the next node, and the last node points back to the first
node.
Assigment:
Write a cpp program that will serve the purpose of a test driver for previously written CLinkedList.h
file. Your program will:
1) Create a choice menu and prompt the user for input. Must be case insensitive!
2) Read the input and call for functions outside of main, in order to perform operations chosen by
the user. These functions involve: Inserting Interger, Removing Interger, Forward Print and
Backward Print.
Requirements and Notes:
1. Forwards Print does not require a subfunction in order to produce output. All the other
operations must call corresponding subfunctions.
2. Nodes of the circular list must be arranged in ascending order.
3. User Input must be processed case insensitive, and implemented using the loop.
4. Document your code completely.
5. CLinkedList.h file contains 3 classes.
- Circular linked lists class with following member functions: constructor, copy constructor,
destructor, assignment operator, insert and remove.
- Node class included in the file header.
- A list iterator class provides a public interface to the list. The pointer points at nodes in the linked
list. Its member functions are as follows:
Constructor: Assigns the linked list data member to the parameter, a reference to a circular linked
list.
begin() sets the iterator to the first node of the linked list (or NULL if the list is empty)
isEmpty() returns whether or not the wrapped linked list is empty
isFirstNode() returns whether the present node is the first node of the linked list
isLastNode() returns whether the present node is the last node of the linked list
operator*() returns the data of the node currently pointed at. (You need 2)
operator++() pre-increment operator advances the pointer to the next node in the list, if there is
one
operator++(int) post-increment operator advances the pointer to the next node in the list, if there
is one
6. Insert function must give feedback where it says the position of where the int was inserted for
example: "Inserting 25 in the middle."
7. Remove function must give either one of these types of feedback:
- "Removing 25" if the int given by the user was found in the list
-"Cannot find 25" if it was not. The program will then move the user back to the choice menu.
Files:
// File: Node.h
// Singly-linked list node definition/implementation (also good for circular)
#ifndef NODE_H
#define NODE_H
// Need to prototype template classes if they are to be friends
template <typename eltType> class CLinkedList;
template <typename eltType> class CListItr;
template <typename eltType> class Node
{ private:
Node(eltType info, Node* link = NULL ) :
data(info), next(link)
{};
eltType data;
Node *next;
friend class CLinkedList<eltType>;
friend c.
Hierarchical Digital Twin of a Naval Power SystemKerry Sado
A hierarchical digital twin of a Naval DC power system has been developed and experimentally verified. Similar to other state-of-the-art digital twins, this technology creates a digital replica of the physical system executed in real-time or faster, which can modify hardware controls. However, its advantage stems from distributing computational efforts by utilizing a hierarchical structure composed of lower-level digital twin blocks and a higher-level system digital twin. Each digital twin block is associated with a physical subsystem of the hardware and communicates with a singular system digital twin, which creates a system-level response. By extracting information from each level of the hierarchy, power system controls of the hardware were reconfigured autonomously. This hierarchical digital twin development offers several advantages over other digital twins, particularly in the field of naval power systems. The hierarchical structure allows for greater computational efficiency and scalability while the ability to autonomously reconfigure hardware controls offers increased flexibility and responsiveness. The hierarchical decomposition and models utilized were well aligned with the physical twin, as indicated by the maximum deviations between the developed digital twin hierarchy and the hardware.
Welcome to WIPAC Monthly the magazine brought to you by the LinkedIn Group Water Industry Process Automation & Control.
In this month's edition, along with this month's industry news to celebrate the 13 years since the group was created we have articles including
A case study of the used of Advanced Process Control at the Wastewater Treatment works at Lleida in Spain
A look back on an article on smart wastewater networks in order to see how the industry has measured up in the interim around the adoption of Digital Transformation in the Water Industry.
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)MdTanvirMahtab2
This presentation is about the working procedure of Shahjalal Fertilizer Company Limited (SFCL). A Govt. owned Company of Bangladesh Chemical Industries Corporation under Ministry of Industries.
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...Amil Baba Dawood bangali
Contact with Dawood Bhai Just call on +92322-6382012 and we'll help you. We'll solve all your problems within 12 to 24 hours and with 101% guarantee and with astrology systematic. If you want to take any personal or professional advice then also you can call us on +92322-6382012 , ONLINE LOVE PROBLEM & Other all types of Daily Life Problem's.Then CALL or WHATSAPP us on +92322-6382012 and Get all these problems solutions here by Amil Baba DAWOOD BANGALI
#vashikaranspecialist #astrologer #palmistry #amliyaat #taweez #manpasandshadi #horoscope #spiritual #lovelife #lovespell #marriagespell#aamilbabainpakistan #amilbabainkarachi #powerfullblackmagicspell #kalajadumantarspecialist #realamilbaba #AmilbabainPakistan #astrologerincanada #astrologerindubai #lovespellsmaster #kalajaduspecialist #lovespellsthatwork #aamilbabainlahore#blackmagicformarriage #aamilbaba #kalajadu #kalailam #taweez #wazifaexpert #jadumantar #vashikaranspecialist #astrologer #palmistry #amliyaat #taweez #manpasandshadi #horoscope #spiritual #lovelife #lovespell #marriagespell#aamilbabainpakistan #amilbabainkarachi #powerfullblackmagicspell #kalajadumantarspecialist #realamilbaba #AmilbabainPakistan #astrologerincanada #astrologerindubai #lovespellsmaster #kalajaduspecialist #lovespellsthatwork #aamilbabainlahore #blackmagicforlove #blackmagicformarriage #aamilbaba #kalajadu #kalailam #taweez #wazifaexpert #jadumantar #vashikaranspecialist #astrologer #palmistry #amliyaat #taweez #manpasandshadi #horoscope #spiritual #lovelife #lovespell #marriagespell#aamilbabainpakistan #amilbabainkarachi #powerfullblackmagicspell #kalajadumantarspecialist #realamilbaba #AmilbabainPakistan #astrologerincanada #astrologerindubai #lovespellsmaster #kalajaduspecialist #lovespellsthatwork #aamilbabainlahore #Amilbabainuk #amilbabainspain #amilbabaindubai #Amilbabainnorway #amilbabainkrachi #amilbabainlahore #amilbabaingujranwalan #amilbabainislamabad
Saudi Arabia stands as a titan in the global energy landscape, renowned for its abundant oil and gas resources. It's the largest exporter of petroleum and holds some of the world's most significant reserves. Let's delve into the top 10 oil and gas projects shaping Saudi Arabia's energy future in 2024.
Water scarcity is the lack of fresh water resources to meet the standard water demand. There are two type of water scarcity. One is physical. The other is economic water scarcity.
Final project report on grocery store management system..pdfKamal Acharya
In today’s fast-changing business environment, it’s extremely important to be able to respond to client needs in the most effective and timely manner. If your customers wish to see your business online and have instant access to your products or services.
Online Grocery Store is an e-commerce website, which retails various grocery products. This project allows viewing various products available enables registered users to purchase desired products instantly using Paytm, UPI payment processor (Instant Pay) and also can place order by using Cash on Delivery (Pay Later) option. This project provides an easy access to Administrators and Managers to view orders placed using Pay Later and Instant Pay options.
In order to develop an e-commerce website, a number of Technologies must be studied and understood. These include multi-tiered architecture, server and client-side scripting techniques, implementation technologies, programming language (such as PHP, HTML, CSS, JavaScript) and MySQL relational databases. This is a project with the objective to develop a basic website where a consumer is provided with a shopping cart website and also to know about the technologies used to develop such a website.
This document will discuss each of the underlying technologies to create and implement an e- commerce website.
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdffxintegritypublishin
Advancements in technology unveil a myriad of electrical and electronic breakthroughs geared towards efficiently harnessing limited resources to meet human energy demands. The optimization of hybrid solar PV panels and pumped hydro energy supply systems plays a pivotal role in utilizing natural resources effectively. This initiative not only benefits humanity but also fosters environmental sustainability. The study investigated the design optimization of these hybrid systems, focusing on understanding solar radiation patterns, identifying geographical influences on solar radiation, formulating a mathematical model for system optimization, and determining the optimal configuration of PV panels and pumped hydro storage. Through a comparative analysis approach and eight weeks of data collection, the study addressed key research questions related to solar radiation patterns and optimal system design. The findings highlighted regions with heightened solar radiation levels, showcasing substantial potential for power generation and emphasizing the system's efficiency. Optimizing system design significantly boosted power generation, promoted renewable energy utilization, and enhanced energy storage capacity. The study underscored the benefits of optimizing hybrid solar PV panels and pumped hydro energy supply systems for sustainable energy usage. Optimizing the design of solar PV panels and pumped hydro energy supply systems as examined across diverse climatic conditions in a developing country, not only enhances power generation but also improves the integration of renewable energy sources and boosts energy storage capacities, particularly beneficial for less economically prosperous regions. Additionally, the study provides valuable insights for advancing energy research in economically viable areas. Recommendations included conducting site-specific assessments, utilizing advanced modeling tools, implementing regular maintenance protocols, and enhancing communication among system components.
2. Linked Lists
A linked list is a linear collection of data elements,
called nodes, where the linear order is given by
means of pointers.
Each node is divided into two parts:
The first part contains the information of the element and
The second part contains the address of the next node (link
/next pointer field) in the list.
4. Adding an Element to the front of a Linked List
5
info next
list
info next info next
3 8 null
5. Some Notations for use in algorithm (Not in C
programs)
p: is a pointer
node(p): the node pointed to by p
info(p): the information portion of the node
next(p): the next address portion of the node
getnode(): obtains an empty node
freenode(p): makes node(p) available for reuse even
if the value of the pointer p is changed.
6. Adding an Element to the front of a Linked List
5
info next
list
info next info next
3 8
info next
p p = getnode()
null
7. Adding an Element to the front of a Linked List
5
info next
list
info next info next
3 8
info next
p 6 info(p) = 6
null
8. Adding an Element to the front of a Linked List
5
info next info next info next
3 8
info next
p 6
list
next(p) = list
null
9. Adding an Element to the front of a Linked List
5
info next info next info next
3 8
info next
6
p
list list = p
null
10. Adding an Element to the front of a Linked List
5
info next info next info next
3 8
info next
list 6 null
11. Removing an Element from the front of a Linked
List
5
info next info next info next
3 8
info next
list 6 null
12. Removing an Element from the front of a Linked
List
5
info next info next info next
3 8
info next
6
list
p
p = list
null
13. Removing an Element from the front of a Linked
List
5
info next info next info next
3 8
info next
6
list
p list = next(p)
null
14. Removing an Element from the front of a Linked
List
5
info next info next info next
3 8
info next
6
list
p x = info(p)
x = 6
null
15. Removing an Element from the front of a Linked
List
5
info next info next info next
3 8
info next
p
x = 6
freenode(p)
list null
16. Removing an Element from the front of a Linked
List
5
info next info next info next
3 8
list
x = 6 null
17. Linked List Implementation of Stacks –
PUSH(S,X)
The first node of the list is the top of the stack. If an
external pointer s points to such a linked list, the
operation push(s,x) may be implemented by
p=getnode();
info(p)=x;
next(p)=s;
s=p;
18. Linked List Implementation of Stacks – POP(S)
The operation x=pop(s) removes the first node from a nonempty list
and signals underflow if the list is empty:
if (empty(s)){ /* checks whether s equals null */
printf(‘stack underflow’);
exit(1);
}
else {
p =s;
s=next(p);
x = info(p);
freenode(p);
}
19. Linked List Implemantation of QUEUES
5
info next info next info next
3 8
info next
6
front null
rear
5
info next info next info next
3 8
info next
6
front
info next
null
rear
12
20. Linked List Implemantation of QUEUES
A queue q consists of a list and two pointers, q.front and q.rear. The operations
empty(q) and x=remove(q) are completely analogous to empty(s) and x=pop(s),
with the pointer q.front replacing s.
if(empty(q)){
printf(“queue undeflow”);
exit(1);
}
p=q.front;
x=info(p);
q.front=next(p);
if(q.front==null)
q.rear=null;
freenode(p);
return(x);
21. Linked List Implemantation of QUEUES
The operation insert(q,x) is implemented by
p= getnode();
info(p)=x;
next(p)=null;
if(q.front==null)
q.front=p;
else
next(q.rear)=p;
q.rear=p;
22. Linked List as a Data Structure
An item is accesses in a linked list by traversing the
list from its beginning.
An array implementation allows acccess to the nth
item in a group using single operation, whereas a list
implementation requires n operations.
The advantage of a list over an array occurs when it
is necessary to insert or delete an element in the
middle of a group of other elements.
23. Element x is inserted between the third an fourth
elements in an array
X0
X1
X2
X3
X4
X5
X6
X0
X1
X2
X3
X4
X5
X6
X0
X1
X2
X3
X4
X5
X6
x
24. Inserting an item x into a list after a node pointed
to by p
X0 X1 X2 X3 X4 X5 X6 null
list
X0 X1 X2 X3 X4 X5 X6 null
list
p
p
x
q
25. Inserting an item x into a list after a node pointed
to by p
q=getnode();
info(q)=x;
next(q)=next(p);
next(p)=q;
26. Deleting an item x from a list after a node
pointed to by p
X0 X1 X2 X3 X4 X5 X6 null
list
p q
X0 X1 X2 X4 X5 X6 null
list
p
x =X3
X3
27. Deleting an item x from a list after a node
pointed to by p
q=next(p);
x=info(q);
next(p)=next(q);
freenode(q);
28. LINKED LISTS USING DYNAMIC VARIABLES
In array implementation of the linked lists a fixed set of nodes represented
by an array is established at the beginning of the execution
A pointer to a node is represented by the relative position of the node
within the array.
In array implementation, it is not possible to determine the number of
nodes required for the linked list. Therefore;
Less number of nodes can be allocated which means that the program will have
overflow problem.
More number of nodes can be allocated which means that some amount of the
memory storage will be wasted.
The solution to this problem is to allow nodes that are dynamic, rather
than static.
When a node is required storage is reserved/allocated for it and when a
node is no longerneeded, the memory storage is released/freed.
29. ALLOCATING AND FREEING DYNAMIC
VARIABLES
C library function malloc() is used for dynamically
allocating a space to a pointer. Note that the malloc() is
a library function in <stdlib.h> header file.
The following lines allocate an integer space from the
memory pointed by the pointer p.
int *p;
p = (int *) malloc(sizeof(int));
Note that sizeof() is another library function that returns the
number of bytes required for the operand. In this example, 4
bytes for the int.
30. ALLOCATING AND FREEING DYNAMIC
VARIABLES
Allocate floating point number space for a float
pointer f.
float *f;
f = (float *) malloc(sizeof(float));
31. Question:What is the output of the following
lines?
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);
The above lines will print 3 and 6.
p
p 3
6
x
q
q 6
32. malloc() and free()
The following lines and the proceeding figure shows the
effectiveness 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);
33. LINKED LISTS STRUCTURES AND BASIC
FUNCTIONS
The value zero can be used in a C program as the null pointer. You can
use the following line to declare the NULL constant. Note that a NULL
pointer is considered NOT to point any storage location.
#define NULL 0
The following node structure can be used to implement Linked Lists.
Note that the info field, which can be some other data type (not
necessarily int), keeps the data of the node and the pointer next links
the node to the next node in the Linked List.
struct node{
int info;
struct node *next;
};
typedef struct node *NODEPTR;
34. LINKED LISTS STRUCTURES AND BASIC
FUNCTIONS
When a new node is required (e.g. to be inserted into
the list) the following function, getnode, can be used
to make a new node to be available for the list.
NODEPTR getnode(void)
{
NODEPTR p;
p = (NODEPTR) malloc(sizeof(struct node));
return p;
}
35. LINKED LISTS STRUCTURES AND BASIC
FUNCTIONS
When a new node is no longer used (e.g. to be
deleted from the list) the following function,
freenode, can be used to release the node back to
the memory.
void freenode(NODEPTR p)
{
free(p);
}
36. PRIMITIVE FUNCTIONS FOR LINEAR LINKED
LISTS
The following functions insertafter(p,x) and
delafter(p,px) are primitive functions that can be
used for the dynamic implementation of a linked list.
Assume that list is a pointer variable pointing the
first node of a list (if any) and equals NULL in the
case of an empty list.
39. Searching through the linked list.
The following function searches through the linked
list and returns a pointer the first occurrence of the
search key or returns NULL pointer if the search key
is not in the list. Note that the linked list contains
integer data items.
40. NODEPTR searchList(NODEPTR plist, int key)
{
NODEPTR p;
p = plist;
while(p != NULL){
if(p->info == key)
return p;
p = p->next;
}
return NULL;
}
For more detail contact us