SlideShare a Scribd company logo
1 of 48
List, (dynamic) linked list
Let’s first forget about ‘classes’, but only a dynamic list.
We make lists with ‘classes’ afterwards.
A simple list Example:
using a dynamic array
 concept of a list, e.g. a list of integers
 Print out info
 Empty test
 Search an element
 Insertion (at head, at end, any position)
 Deletion
 …
 implemented
 by a static array (over-sized if necessary)
int list[1000]; int size;
 by a dynamic array
int list[size]; int size;
 by a linked list and more …
int main() {
cout << "Enter list size: ";
int n;
cin >> n;
int* A = new int[n];
initialize(A, n, 0);
print(A, n);
A = addEnd(A,n,5);
print(A, n);
A = addHead(A,n,5);
print(A, n);
A = deleteFirst(A,n);
print(A, n);
selectionSort(A, n);
print(A, n);
delete [] A;
}
How to use a list?
int A[10000];
int n;
Nothing compulsory in
programming, only style matters!
Initialize
void initialize(int list[], int size, int value){
for(int i=0; i<size; i++)
list[i] = value;
}
void print(int list[], int size) {
cout << "[ ";
for(int i=0; i<size; i++)
cout << list[i] << " ";
cout << "]" << endl;
}
Print out a list
Delete the first element
// for deleting the first element of the array
int* deleteFirst(int list[], int& size){
int* newList;
newList = new int[size-1]; // make new array
if(size){ // copy and delete old array
for(int i=0; i<size-1; i++)
newList[i] = list[i+1];
delete [] list;
}
size--;
return newList;
}
Instead of
A = deleteFirst(A,n)
we can also just
deleteFirst(A,n) if we define as a void type function:
void deleteFirst(int*& A, int& size) {
…
A = newList;
}
Remark:
We can also B = deleteFirst(A,n) if we keep the original intact
Adding Elements
// for adding a new element to end of array
int* addEnd(int list[], int& size, int value){
int* newList;
newList = new int [size+1]; // make new array
if(size){ // copy and delete old array
for(int i=0; i<size; i++)
newList[i] = list[i];
delete [] list;
}
newList[size] = value;
size++;
return newList;
}
// for adding a new element at the beginning of the array
int* addHead(int list[], int& size, int value){
int* newList;
newList = new int [size+1]; // make new array
if(size){ // copy and delete old array
for(int i=0; i<size; i++)
newList[i+1] = list[i];
delete [] list;
}
newList[0] = value;
size++;
return newList;
}
Add at the beginning:
Linked list: a dynamic list
Motivation
 list using static array
int myArray[1000];
int n;
We have to decide (to oversize) in advance the size of the array
(list)
 list using dynamic array
int* myArray;
int n;
cin >> n;
myArray = new int[n];
We allocate an array (list) of any specified size while the
program is running
 linked-list (dynamic size)
size = ??
The list is dynamic. It can grow and shrink to any size.
Array naturally represents a (ordered) list,
the link is implicit, consecutive and contiguous!
Now the link is explicit, any places!
20 45 75 85
Data
Link
20
45
75
85
Data
Link
20 45 75 85
Data Link
0 1 2 array
linked list
Linked Lists: Basic Idea
 A linked list is an ordered collection of data
 Each element of the linked list has
 Some data
 A link to the next element
 The link is used to chain the data
Example: A linked list of integers:
20 45 75 85
Data Link
 The list can grow and shrink
Linked Lists: Basic Ideas
20 45 75 85
20 45
addEnd(75), addEnd(85)
deleteEnd(85), deleteHead(20), deleteHead(45)
75
 Original linked list of integers:
 Insertion (in the middle):
 Deletion (in the middle)
Linked Lists: Operations
20 45 75 85
20 45 75 85
20 45 75 85
60
old value
deleted item
struct Node{
int data;
Node* next;
};
We can also:
typedef Node* NodePtr;
Definition of linked list type:
Linked List Structure
 Node : Data + Link
 Definition
struct Node {
int data; //contains useful information
Node* next; //points to next element or NULL
};
 Create a Node
Node* p;
p = new Node; //points to newly allocated memory
 Delete a Node
delete p;
 Access fields in a node
(*p).data; //access the data field
(*p).next; //access the pointer field
Or it can be accessed this way
p->data //access the data field
p->next //access the pointer field
Representing and
accessing linked lists
 We define a pointer
Node* head;
that points to the first node of the linked list. When the
linked list is empty then head is NULL.
20 45 75 85
Head
Passing a Linked List
to a Function
 When passing a linked list to a function it should suffice to pass
the value of head. Using the value of head the function can
access the entire list.
 Problem: If a function changes the beginning of a list by inserting
or deleting a node, then head will no longer point to the beginning
of the list.
 Solution: When passing head always pass it by reference (not
good!)
or using a function to return a new pointer value
It is roughly the same as for an array!!!
Implementation of an
(Unsorted) Linked List
Start the first node
from scratch
Node* newPtr;
newPtr = new Node;
newPtr->data = 20;
newPtr->next = NULL;
head = newPtr;
Head
newPtr
20
Head
head = NULL;
Inserting a Node
at the Beginning
newPtr = new Node;
newPtr->data = 13;
newPtr->next = Head;
head = newPtr;
Head
newPtr
13
20
Keep going …
Head
newPtr
50 40 13 20
void addHead(Node*& head, int newdata){
Node* newPtr = new Node;
newPtr->data = newdata;
newPtr->next = Head;
head = newPtr;
}
Adding an element to the head:
Call by reference, scaring!!!
NodePtr&
Node* addHead(Node* head, int newdata){
Node* newPtr = new Node;
newPtr->data = newdata;
newPtr->next = Head;
return newPtr;
}
Also written (more functionally) as:
Compare it with ‘addHead’ with a dynamic array implementation
(to delete)
Deleting the Head Node
Node* p;
p = head;
head = head->next;
delete p;
head
p
50 40 13 20
void deleteHead(Node*& head){
if(head != NULL){
NodePtr p = head;
head = head->next;
delete p;
}
}
Node* deleteHead(Node* head){
if(head != NULL){
NodePtr p = head;
head = head->next;
delete p;
}
return head;
}
As a function:
Displaying a Linked List
p = head;
p = p->next;
20 45
head
p
20 45
head
p
void displayList(Node* head){
NodePtr p;
p = head;
while(p != NULL){
cout << p->data << endl;
p = p->next;
}
}
A linked list is displayed by walking through its nodes one by one,
and displaying their data fields (similar to an array!).
void displayArray(int data[], int size) {
int n=0;
while ( n<size ) {
cout << data[i] << endl;
n++;
}
}
For an array:
//return the pointer of the node that has data=item
//return NULL if item does not exist
Node* searchNode(Node* head, int item){
NodePtr p = head;
NodePtr result = NULL;
bool found=false;
while((p != NULL) && (!found)){
if(p->data == item) {
found = true;
result = p;}
p = p->next;
}
return result;
}
Searching for a node (look at array
searching first!)
void main() {
const int size=8;
int data[size] = { 10, 7, 9, 1, 17, 30, 5, 6 };
int value;
cout << "Enter search element: ";
cin >> value;
int n=0;
int position=-1;
bool found=false;
while ( (n<size) && (!found) ) {
if(data[n] == value) {
found=true;
position=n;}
n++;
}
if(position==-1) cout << "Not found!!n";
else cout << "Found at: " << position << endl;
}
Remember array searching algorithm:
It is essentially the same!
Variations of linked lists
 Unsorted linked lists
 Sorted linked lists
 Circular linked lists
 Doubly linked lists
 …
Further considerations for the
unsorted lists:
 Physical copy of list for operators like
‘deleteHead’ and ‘addHead’
 ‘deleteHead’ should be understood as a
decomposition into a sub-list …
Node* deleteHead(Node* head){
// physically copy head into a new one, newhead
// so to keep the original list intact!
Node* newhead=NULL;
Node* temp=head;
while(temp!=NULL) {
newhead=addEnd(newhead,temp->data);
temp=temp->next;
}
if(newhead != NULL){
Node* p = newhead;
newhead = newhead->next;
delete p;
}
return newhead;
}
B = deleteHead(A);
 Original linked list of integers:
 Add to the end (insert at the end):
More operation:
adding to the end
50 40 13 20
50 40 13 20 60
Last element
The key is how to locate the last element or node of the list!
void addEnd(NodePtr& head, int newdata){
NodePtr newPtr = new Node;
newPtr->data = newdata;
newPtr->next = NULL;
NodePtr last = head;
if(last != NULL){ // general non-empty list case
while(last->next != NULL)
last=last->next;
last->next = newPtr;
}
else // deal with the case of empty list
head = newPtr;
}
Add to the end:
Link new object to last->next
Link a new object to empty list
NodePtr addEnd(NodePtr head, int newdata){
NodePtr newPtr = new Node;
newPtr->data = newdata;
newPtr->next = NULL;
NodePtr last = head;
if(last != NULL){ // general non-empty list case
while(last->next != NULL)
last=last->next;
last->next = newPtr;
}
else// deal with the case of empty list
head = newPtr;
return head;
}
Add to the end as a function:
Implementation of a
Sorted Linked List
Inserting a Node
Head
cur
20
33
45 75
prev
...
newPtr
1. (a) Create a new node using:
NodePtr newPtr = new node;
(b) Fill in the data field correctly.
2. Find “prev” and “cur” such that
the new node should be inserted between *prev and *cur.
3. Connect the new node to the list by using:
(a) newPtr->next = cur;
(b) prev->next = newPtr;
Finding prev and cur
Suppose that we want to insert or delete a node with
data value newValue. Then the following code
successfully finds prev and cur such that
prev->data < newValue <= cur->data
prev = NULL;
cur = head;
found=false;
while( (cur!=NULL) && (!found) ) {
if (newValue > cur->data) {
prev=cur;
cur=cur->next;
}
else found = true;
}
Prev is necessary as we can’t go back!
It’s a kind of search algo,
prev = NULL;
cur = head;
while( (cur!=NULL) && (newValue>cur->data) ) {
prev=cur;
cur=cur->next;
}
Logical AND (&&) is short-circuited, sequential, i.e. if the first
part is false, the second part will not be executed.
Finally, it is equivalent to:
//insert item into linked list according to ascending order
Node* insertNode(Node* head, int item){
NodePtr newp, cur, pre;
newp = new Node;
newp->data = item;
pre = NULL;
cur = head;
while( (cur != NULL) && (item>cur->data)){
pre = cur;
cur = cur->next;
}
if(pre == NULL){ //insert to head of linked list
newp->next = head;
head = newp;
} else {
pre->next = newp;
new->next = cur;
}
return head;
}
If the position happens to be the head
General case
// not recommended void type function
void insertNode(NodePtr& head, int item){
NodePtr newp, cur, pre;
newp = new Node;
newp->data = item;
pre = NULL;
cur = head;
while( (cur != NULL) && (item>cur->data)){
pre = cur;
cur = cur->next;
}
if(pre == NULL){ //insert to head of linked list
newp->next = head;
head = newp;
} else {
pre->next = newp;
new->next = cur;
}
}
(to delete)
Deleting a Node
 To delete a node from the list
1. Locate the node to be deleted
(a) cur points to the node.
(b) prev points to its predecessor
2. Disconnect node from list using:
prev->next = cur->next;
3. Return deleted node to system:
delete cur;
Head
cur
20 45 75 85
prev
...
Node* deleteNode(Node* head, int item){
NodePtr prev=NULL, cur = head;
while( (cur!=NULL) && (item > cur->data)){
prev = cur;
cur = cur->next;
}
if ( cur!==NULL && cur->data==item) {
if(cur==head)
head = head->next;
else
prev->next = cur->next;
delete cur;
}
return head;
}
Delete an element in a sorted linked list:
If the element is at the head
General case
We can delete only if the element is present!
If (cur==NULL || cur->data!=item) Item is not in the list!
Get the location
void deleteNode(NodePtr& head, int item){
NodePtr prev=NULL, cur = head;
while( (cur!=NULL) && (item > cur->data)){
prev = cur;
cur = cur->next;
}
if ( cur!==NULL && cur->data==item) {
if(cur==Head)
Head = Head->next;
else
prev->next = cur->next;
delete cur;
}
}
// in a void function, not recommended
If the element is at the head
General case
We can delete only if the element is present!
If (cur==NULL || cur->data!=item) Item is not in the list!
Get the location

More Related Content

Similar to DYNAMIC LIST

Data Structures in C++I am really new to C++, so links are really .pdf
Data Structures in C++I am really new to C++, so links are really .pdfData Structures in C++I am really new to C++, so links are really .pdf
Data Structures in C++I am really new to C++, so links are really .pdfrohit219406
 
In C++Write a recursive function to determine whether or not a Lin.pdf
In C++Write a recursive function to determine whether or not a Lin.pdfIn C++Write a recursive function to determine whether or not a Lin.pdf
In C++Write a recursive function to determine whether or not a Lin.pdfflashfashioncasualwe
 
linked List.docx vhjgvjhvgjhjhbbjkhkjhkjh
linked List.docx vhjgvjhvgjhjhbbjkhkjhkjhlinked List.docx vhjgvjhvgjhjhbbjkhkjhkjh
linked List.docx vhjgvjhvgjhjhbbjkhkjhkjhvasavim9
 
This assignment and the next (#5) involve design and development of a.pdf
This assignment and the next (#5) involve design and development of a.pdfThis assignment and the next (#5) involve design and development of a.pdf
This assignment and the next (#5) involve design and development of a.pdfEricvtJFraserr
 
Revisiting a data structures in detail with linked list stack and queue
Revisiting a data structures in detail with linked list stack and queueRevisiting a data structures in detail with linked list stack and queue
Revisiting a data structures in detail with linked list stack and queuessuser7319f8
 
Let n = size of the hash table hashTable = array of size n, w.pdf
Let n = size of the hash table  hashTable = array of size n, w.pdfLet n = size of the hash table  hashTable = array of size n, w.pdf
Let n = size of the hash table hashTable = array of size n, w.pdfaravlitraders2012
 
Assignment isPage 349-350 #4 and #5 Use the Linked List lab.pdf
Assignment isPage 349-350 #4 and #5 Use the Linked List lab.pdfAssignment isPage 349-350 #4 and #5 Use the Linked List lab.pdf
Assignment isPage 349-350 #4 and #5 Use the Linked List lab.pdffortmdu
 
C++ Doubly-Linked ListsThe goal of the exercise is to implement a.pdf
C++ Doubly-Linked ListsThe goal of the exercise is to implement a.pdfC++ Doubly-Linked ListsThe goal of the exercise is to implement a.pdf
C++ Doubly-Linked ListsThe goal of the exercise is to implement a.pdfpoblettesedanoree498
 
Array linked list.ppt
Array  linked list.pptArray  linked list.ppt
Array linked list.pptWaf1231
 

Similar to DYNAMIC LIST (20)

Data Structures in C++I am really new to C++, so links are really .pdf
Data Structures in C++I am really new to C++, so links are really .pdfData Structures in C++I am really new to C++, so links are really .pdf
Data Structures in C++I am really new to C++, so links are really .pdf
 
Unit7 C
Unit7 CUnit7 C
Unit7 C
 
In C++Write a recursive function to determine whether or not a Lin.pdf
In C++Write a recursive function to determine whether or not a Lin.pdfIn C++Write a recursive function to determine whether or not a Lin.pdf
In C++Write a recursive function to determine whether or not a Lin.pdf
 
linked List.docx vhjgvjhvgjhjhbbjkhkjhkjh
linked List.docx vhjgvjhvgjhjhbbjkhkjhkjhlinked List.docx vhjgvjhvgjhjhbbjkhkjhkjh
linked List.docx vhjgvjhvgjhjhbbjkhkjhkjh
 
This assignment and the next (#5) involve design and development of a.pdf
This assignment and the next (#5) involve design and development of a.pdfThis assignment and the next (#5) involve design and development of a.pdf
This assignment and the next (#5) involve design and development of a.pdf
 
Revisiting a data structures in detail with linked list stack and queue
Revisiting a data structures in detail with linked list stack and queueRevisiting a data structures in detail with linked list stack and queue
Revisiting a data structures in detail with linked list stack and queue
 
Adt of lists
Adt of listsAdt of lists
Adt of lists
 
List
ListList
List
 
Let n = size of the hash table hashTable = array of size n, w.pdf
Let n = size of the hash table  hashTable = array of size n, w.pdfLet n = size of the hash table  hashTable = array of size n, w.pdf
Let n = size of the hash table hashTable = array of size n, w.pdf
 
Abstract data types
Abstract data typesAbstract data types
Abstract data types
 
CSE240 Doubly Linked Lists
CSE240 Doubly Linked ListsCSE240 Doubly Linked Lists
CSE240 Doubly Linked Lists
 
Assignment isPage 349-350 #4 and #5 Use the Linked List lab.pdf
Assignment isPage 349-350 #4 and #5 Use the Linked List lab.pdfAssignment isPage 349-350 #4 and #5 Use the Linked List lab.pdf
Assignment isPage 349-350 #4 and #5 Use the Linked List lab.pdf
 
C++ Doubly-Linked ListsThe goal of the exercise is to implement a.pdf
C++ Doubly-Linked ListsThe goal of the exercise is to implement a.pdfC++ Doubly-Linked ListsThe goal of the exercise is to implement a.pdf
C++ Doubly-Linked ListsThe goal of the exercise is to implement a.pdf
 
Linked List.pptx
Linked List.pptxLinked List.pptx
Linked List.pptx
 
Data structure
Data  structureData  structure
Data structure
 
Linked lists a
Linked lists aLinked lists a
Linked lists a
 
Array linked list.ppt
Array  linked list.pptArray  linked list.ppt
Array linked list.ppt
 
03-Lists.ppt
03-Lists.ppt03-Lists.ppt
03-Lists.ppt
 
C Exam Help
C Exam Help C Exam Help
C Exam Help
 
Lab-2.4 101.pdf
Lab-2.4 101.pdfLab-2.4 101.pdf
Lab-2.4 101.pdf
 

More from ssuser0be977

IBM list NM portal not updategbbbbbnnmhhh
IBM list NM portal not updategbbbbbnnmhhhIBM list NM portal not updategbbbbbnnmhhh
IBM list NM portal not updategbbbbbnnmhhhssuser0be977
 
lect23_optimization.ppt
lect23_optimization.pptlect23_optimization.ppt
lect23_optimization.pptssuser0be977
 
CS540-2-lecture11 - Copy.ppt
CS540-2-lecture11 - Copy.pptCS540-2-lecture11 - Copy.ppt
CS540-2-lecture11 - Copy.pptssuser0be977
 
wk1a-basicstats.ppt
wk1a-basicstats.pptwk1a-basicstats.ppt
wk1a-basicstats.pptssuser0be977
 
wk1a-basicstats (2).ppt
wk1a-basicstats (2).pptwk1a-basicstats (2).ppt
wk1a-basicstats (2).pptssuser0be977
 

More from ssuser0be977 (8)

IBM list NM portal not updategbbbbbnnmhhh
IBM list NM portal not updategbbbbbnnmhhhIBM list NM portal not updategbbbbbnnmhhh
IBM list NM portal not updategbbbbbnnmhhh
 
lect23_optimization.ppt
lect23_optimization.pptlect23_optimization.ppt
lect23_optimization.ppt
 
CS540-2-lecture11 - Copy.ppt
CS540-2-lecture11 - Copy.pptCS540-2-lecture11 - Copy.ppt
CS540-2-lecture11 - Copy.ppt
 
wk1a-basicstats.ppt
wk1a-basicstats.pptwk1a-basicstats.ppt
wk1a-basicstats.ppt
 
wk1a-basicstats (2).ppt
wk1a-basicstats (2).pptwk1a-basicstats (2).ppt
wk1a-basicstats (2).ppt
 
lect08.ppt
lect08.pptlect08.ppt
lect08.ppt
 
11CS10033.pptx
11CS10033.pptx11CS10033.pptx
11CS10033.pptx
 
dsa1.ppt
dsa1.pptdsa1.ppt
dsa1.ppt
 

Recently uploaded

Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 

Recently uploaded (20)

Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 

DYNAMIC LIST

  • 1. List, (dynamic) linked list Let’s first forget about ‘classes’, but only a dynamic list. We make lists with ‘classes’ afterwards.
  • 2. A simple list Example: using a dynamic array  concept of a list, e.g. a list of integers  Print out info  Empty test  Search an element  Insertion (at head, at end, any position)  Deletion  …  implemented  by a static array (over-sized if necessary) int list[1000]; int size;  by a dynamic array int list[size]; int size;  by a linked list and more …
  • 3. int main() { cout << "Enter list size: "; int n; cin >> n; int* A = new int[n]; initialize(A, n, 0); print(A, n); A = addEnd(A,n,5); print(A, n); A = addHead(A,n,5); print(A, n); A = deleteFirst(A,n); print(A, n); selectionSort(A, n); print(A, n); delete [] A; } How to use a list? int A[10000]; int n; Nothing compulsory in programming, only style matters!
  • 4. Initialize void initialize(int list[], int size, int value){ for(int i=0; i<size; i++) list[i] = value; }
  • 5. void print(int list[], int size) { cout << "[ "; for(int i=0; i<size; i++) cout << list[i] << " "; cout << "]" << endl; } Print out a list
  • 6. Delete the first element // for deleting the first element of the array int* deleteFirst(int list[], int& size){ int* newList; newList = new int[size-1]; // make new array if(size){ // copy and delete old array for(int i=0; i<size-1; i++) newList[i] = list[i+1]; delete [] list; } size--; return newList; }
  • 7. Instead of A = deleteFirst(A,n) we can also just deleteFirst(A,n) if we define as a void type function: void deleteFirst(int*& A, int& size) { … A = newList; } Remark: We can also B = deleteFirst(A,n) if we keep the original intact
  • 8. Adding Elements // for adding a new element to end of array int* addEnd(int list[], int& size, int value){ int* newList; newList = new int [size+1]; // make new array if(size){ // copy and delete old array for(int i=0; i<size; i++) newList[i] = list[i]; delete [] list; } newList[size] = value; size++; return newList; }
  • 9. // for adding a new element at the beginning of the array int* addHead(int list[], int& size, int value){ int* newList; newList = new int [size+1]; // make new array if(size){ // copy and delete old array for(int i=0; i<size; i++) newList[i+1] = list[i]; delete [] list; } newList[0] = value; size++; return newList; } Add at the beginning:
  • 10. Linked list: a dynamic list
  • 11. Motivation  list using static array int myArray[1000]; int n; We have to decide (to oversize) in advance the size of the array (list)  list using dynamic array int* myArray; int n; cin >> n; myArray = new int[n]; We allocate an array (list) of any specified size while the program is running  linked-list (dynamic size) size = ?? The list is dynamic. It can grow and shrink to any size.
  • 12. Array naturally represents a (ordered) list, the link is implicit, consecutive and contiguous! Now the link is explicit, any places! 20 45 75 85 Data Link 20 45 75 85 Data Link 20 45 75 85 Data Link 0 1 2 array linked list
  • 13. Linked Lists: Basic Idea  A linked list is an ordered collection of data  Each element of the linked list has  Some data  A link to the next element  The link is used to chain the data Example: A linked list of integers: 20 45 75 85 Data Link
  • 14.  The list can grow and shrink Linked Lists: Basic Ideas 20 45 75 85 20 45 addEnd(75), addEnd(85) deleteEnd(85), deleteHead(20), deleteHead(45) 75
  • 15.  Original linked list of integers:  Insertion (in the middle):  Deletion (in the middle) Linked Lists: Operations 20 45 75 85 20 45 75 85 20 45 75 85 60 old value deleted item
  • 16. struct Node{ int data; Node* next; }; We can also: typedef Node* NodePtr; Definition of linked list type:
  • 17. Linked List Structure  Node : Data + Link  Definition struct Node { int data; //contains useful information Node* next; //points to next element or NULL };  Create a Node Node* p; p = new Node; //points to newly allocated memory  Delete a Node delete p;
  • 18.  Access fields in a node (*p).data; //access the data field (*p).next; //access the pointer field Or it can be accessed this way p->data //access the data field p->next //access the pointer field
  • 19. Representing and accessing linked lists  We define a pointer Node* head; that points to the first node of the linked list. When the linked list is empty then head is NULL. 20 45 75 85 Head
  • 20. Passing a Linked List to a Function  When passing a linked list to a function it should suffice to pass the value of head. Using the value of head the function can access the entire list.  Problem: If a function changes the beginning of a list by inserting or deleting a node, then head will no longer point to the beginning of the list.  Solution: When passing head always pass it by reference (not good!) or using a function to return a new pointer value It is roughly the same as for an array!!!
  • 22. Start the first node from scratch Node* newPtr; newPtr = new Node; newPtr->data = 20; newPtr->next = NULL; head = newPtr; Head newPtr 20 Head head = NULL;
  • 23. Inserting a Node at the Beginning newPtr = new Node; newPtr->data = 13; newPtr->next = Head; head = newPtr; Head newPtr 13 20
  • 25. void addHead(Node*& head, int newdata){ Node* newPtr = new Node; newPtr->data = newdata; newPtr->next = Head; head = newPtr; } Adding an element to the head: Call by reference, scaring!!! NodePtr&
  • 26. Node* addHead(Node* head, int newdata){ Node* newPtr = new Node; newPtr->data = newdata; newPtr->next = Head; return newPtr; } Also written (more functionally) as: Compare it with ‘addHead’ with a dynamic array implementation
  • 27. (to delete) Deleting the Head Node Node* p; p = head; head = head->next; delete p; head p 50 40 13 20
  • 28. void deleteHead(Node*& head){ if(head != NULL){ NodePtr p = head; head = head->next; delete p; } } Node* deleteHead(Node* head){ if(head != NULL){ NodePtr p = head; head = head->next; delete p; } return head; } As a function:
  • 29. Displaying a Linked List p = head; p = p->next; 20 45 head p 20 45 head p
  • 30. void displayList(Node* head){ NodePtr p; p = head; while(p != NULL){ cout << p->data << endl; p = p->next; } } A linked list is displayed by walking through its nodes one by one, and displaying their data fields (similar to an array!). void displayArray(int data[], int size) { int n=0; while ( n<size ) { cout << data[i] << endl; n++; } } For an array:
  • 31. //return the pointer of the node that has data=item //return NULL if item does not exist Node* searchNode(Node* head, int item){ NodePtr p = head; NodePtr result = NULL; bool found=false; while((p != NULL) && (!found)){ if(p->data == item) { found = true; result = p;} p = p->next; } return result; } Searching for a node (look at array searching first!)
  • 32. void main() { const int size=8; int data[size] = { 10, 7, 9, 1, 17, 30, 5, 6 }; int value; cout << "Enter search element: "; cin >> value; int n=0; int position=-1; bool found=false; while ( (n<size) && (!found) ) { if(data[n] == value) { found=true; position=n;} n++; } if(position==-1) cout << "Not found!!n"; else cout << "Found at: " << position << endl; } Remember array searching algorithm: It is essentially the same!
  • 33. Variations of linked lists  Unsorted linked lists  Sorted linked lists  Circular linked lists  Doubly linked lists  …
  • 34. Further considerations for the unsorted lists:  Physical copy of list for operators like ‘deleteHead’ and ‘addHead’  ‘deleteHead’ should be understood as a decomposition into a sub-list …
  • 35. Node* deleteHead(Node* head){ // physically copy head into a new one, newhead // so to keep the original list intact! Node* newhead=NULL; Node* temp=head; while(temp!=NULL) { newhead=addEnd(newhead,temp->data); temp=temp->next; } if(newhead != NULL){ Node* p = newhead; newhead = newhead->next; delete p; } return newhead; } B = deleteHead(A);
  • 36.  Original linked list of integers:  Add to the end (insert at the end): More operation: adding to the end 50 40 13 20 50 40 13 20 60 Last element The key is how to locate the last element or node of the list!
  • 37. void addEnd(NodePtr& head, int newdata){ NodePtr newPtr = new Node; newPtr->data = newdata; newPtr->next = NULL; NodePtr last = head; if(last != NULL){ // general non-empty list case while(last->next != NULL) last=last->next; last->next = newPtr; } else // deal with the case of empty list head = newPtr; } Add to the end: Link new object to last->next Link a new object to empty list
  • 38. NodePtr addEnd(NodePtr head, int newdata){ NodePtr newPtr = new Node; newPtr->data = newdata; newPtr->next = NULL; NodePtr last = head; if(last != NULL){ // general non-empty list case while(last->next != NULL) last=last->next; last->next = newPtr; } else// deal with the case of empty list head = newPtr; return head; } Add to the end as a function:
  • 40. Inserting a Node Head cur 20 33 45 75 prev ... newPtr 1. (a) Create a new node using: NodePtr newPtr = new node; (b) Fill in the data field correctly. 2. Find “prev” and “cur” such that the new node should be inserted between *prev and *cur. 3. Connect the new node to the list by using: (a) newPtr->next = cur; (b) prev->next = newPtr;
  • 41. Finding prev and cur Suppose that we want to insert or delete a node with data value newValue. Then the following code successfully finds prev and cur such that prev->data < newValue <= cur->data
  • 42. prev = NULL; cur = head; found=false; while( (cur!=NULL) && (!found) ) { if (newValue > cur->data) { prev=cur; cur=cur->next; } else found = true; } Prev is necessary as we can’t go back! It’s a kind of search algo,
  • 43. prev = NULL; cur = head; while( (cur!=NULL) && (newValue>cur->data) ) { prev=cur; cur=cur->next; } Logical AND (&&) is short-circuited, sequential, i.e. if the first part is false, the second part will not be executed. Finally, it is equivalent to:
  • 44. //insert item into linked list according to ascending order Node* insertNode(Node* head, int item){ NodePtr newp, cur, pre; newp = new Node; newp->data = item; pre = NULL; cur = head; while( (cur != NULL) && (item>cur->data)){ pre = cur; cur = cur->next; } if(pre == NULL){ //insert to head of linked list newp->next = head; head = newp; } else { pre->next = newp; new->next = cur; } return head; } If the position happens to be the head General case
  • 45. // not recommended void type function void insertNode(NodePtr& head, int item){ NodePtr newp, cur, pre; newp = new Node; newp->data = item; pre = NULL; cur = head; while( (cur != NULL) && (item>cur->data)){ pre = cur; cur = cur->next; } if(pre == NULL){ //insert to head of linked list newp->next = head; head = newp; } else { pre->next = newp; new->next = cur; } }
  • 46. (to delete) Deleting a Node  To delete a node from the list 1. Locate the node to be deleted (a) cur points to the node. (b) prev points to its predecessor 2. Disconnect node from list using: prev->next = cur->next; 3. Return deleted node to system: delete cur; Head cur 20 45 75 85 prev ...
  • 47. Node* deleteNode(Node* head, int item){ NodePtr prev=NULL, cur = head; while( (cur!=NULL) && (item > cur->data)){ prev = cur; cur = cur->next; } if ( cur!==NULL && cur->data==item) { if(cur==head) head = head->next; else prev->next = cur->next; delete cur; } return head; } Delete an element in a sorted linked list: If the element is at the head General case We can delete only if the element is present! If (cur==NULL || cur->data!=item) Item is not in the list! Get the location
  • 48. void deleteNode(NodePtr& head, int item){ NodePtr prev=NULL, cur = head; while( (cur!=NULL) && (item > cur->data)){ prev = cur; cur = cur->next; } if ( cur!==NULL && cur->data==item) { if(cur==Head) Head = Head->next; else prev->next = cur->next; delete cur; } } // in a void function, not recommended If the element is at the head General case We can delete only if the element is present! If (cur==NULL || cur->data!=item) Item is not in the list! Get the location