SlideShare uma empresa Scribd logo
1 de 10
Baixar para ler offline
Lecture Notes Data Structures and Algorithms
 
Maryam Amin, Assistant Professor, BIIT 1/10
 
Lecture 4 to 5
 
Contents
• Linked List
• Memory Representation
• Operations on Linked List
• Traversing
• Searching
• Insertion
o Node Insertion At Start
o Node Insertion At End
o Node Insertion after a specified location
• Deletion
o Deletion of first node
o Deletion of last Node
o Deletion of a specified Node
• Count number of Node
• Insert a new Node as tenth Node
• Delete tenth Node
• Advantages of Link list
• Disadvantages of Link list
Linked List
This is most widely used data structure and also very much practical one. Here the elements
(nodes) are kept in disjoint memory locations. Each node consists of two parts one for the data
and other for address of next node. In array approach which is hardly used but just to clarify the
concept. One might be kept for data portion and second for maintaining the appropriate address
to next node. As shown in figure below.
Lecture Notes Data Structures and Algorithms
 
Maryam Amin, Assistant Professor, BIIT 2/10
 
1 W 5
2 S 3
3 I 4
4 F NULL
5 A 2
But this does not reveal the actual meaning of linked list so we go for a pointer approach. Let
us consider the operations of insertion and deletion in a sequentially allocated list. Assume that
we have an n-element list and that it is required to insert a new element between the second and
the third elements. In this case, the last n – 2 elements of the list must be physically moved to
make room for the new element. For large-sized lists, which are subjected to many insertions,
this insertion approach can be very costly. The same conclusion holds in the case of deletion,
since all elements after the deleted element must be moved up so as to use the vacated space
caused by the deletion.
These two allocation methods (linked and sequential) can be compared with respect to
other operations as well. For a search operation in a linked list, we must follow the link from the
first node onwards until the desired node is found. This operation is certainly inferior to the
computed-address method of locating an element in a sequentially allocated list. If we want to
split or join two linked lists, then these operations involve the changing of pointer fields without
having to move any nodes. Such is not the case for sequentially allocated counterparts.
Clearly, pointers or links consume additional memory. The cost of this additional memory
becomes less important as the information contents of a node require more memory. In the above
discussion the actual address of a node was used in the link field for illustration purposes. In
practice, however, this address may be of no concern (and indeed unknown) to the programmer.
Therefore, in the remainder of our discussion of linked structure, the arrow symbol is used
exclusively to denote a successor node.
The use of pointers is only to specify the relationship of logical adjacency among
elements of a linear list. This is an important point to emphasize – the notion of logical adjacency
versus physical adjacency. In vector (or sequential) storage, they are the same. In linked storage,
they are not. Therefore, we have more flexibility with linked storage.
Lecture Notes Data Structures and Algorithms
 
Maryam Amin, Assistant Professor, BIIT 3/10
 
Memory Representation
A linked list provides a more flexible storage system in that it doesn’t use array at all.
Instead, space for each data item is obtained as needed with new, and each item is connected or
linked, to the next data item using a pointer. The individual item don’t need to be located in the
memory contiguously, the way arrays are; they can be scattered anywhere.
struct link   {                                 // node of list 
   int data;                          //data item 
 link* next;                      //pointer to next link 
   }; 
 
// class of Linked List 
class linklist   {                       //a linked list 
   private: 
      link* first;                    //pointer to first link 
   public: 
     linklist()                      //no‐argument constructor 
         { first = NULL; }            //no first link 
   }; 
Operations on Linked List
Following are the major operations on linked lists.
1. Traversing
Following C++ code is used to traverse a linked list.
void linklist::display()   {           //display all links 
   link* current = first;             //set ptr to first link 
   while( current != NULL )    {       //quit on last link 
      cout << current‐>data << endl;  //print data 
      current = current‐>next;        //move to next link 
      } 
   } 
2. Searching
Following C++ code is used to traverse a linked list.
Lecture Notes Data Structures and Algorithms
 
Maryam Amin, Assistant Professor, BIIT 4/10
 
void linklist::search(int d)   {           //display all links 
        if (first == NULL) { 
                cout << “List is empty”; 
                return; 
        } 
        int loc=0; 
   link* current = first;             //set ptr to first link 
   while( current != NULL )    {       //quit on last link 
             if (current‐>data == d) { 
                  cout << “Item found” << endl;  
                  loc=1; 
             } 
             current = current‐>next; 
   } 
   if (loc == 0) 
             cout << “Item not found”; 
   } 
3. Insertion
A new node can be inserted in the following ways.
3.1 Node Insertion At Start
Following code inserts a new node at the start of linked list.
void linklist::InsertAtStart(int d)  {         //add data item 
   link* newlink = new link;          //make a new link 
   newlink‐>data = d;                 //give it data 
   newlink‐>next = first;                                
   first = newlink; 
   } 
The given C++ program executes insertion at start.
int main()  { 
 linklist li;       //make linked list 
 li.InsertAtStart(25);    //add four items to list 
 li. InsertAtStart (36); 
 li. InsertAtStart (49); 
li.display(); 
} 
Lecture Notes Data Structures and Algorithms
 
Maryam Amin, Assistant Professor, BIIT 5/10
 
3.2 Node Insertion At End
This approach is simpler it is used for insertion at end.
void linklist::InsertAtEnd(int d)  {         //add data item 
   link* newlink = new link;          //make a new link 
   newlink‐>data = d;                 //give it data 
   newlink‐>next = NULL; 
   if (first == NULL)  { 
          first = newlink; 
   } 
   else { 
          link *current = first; 
          while (current‐>next != NULL) 
                      current = current‐>next; 
          current‐>next = newlink;                   //now first points to this 
  } 
   } 
25  NULL
25  NULL36  &25 
25  NULL 36  &2549  &36 
25  NULL 36  &2549  NUL 
Insertion at start 
(Head) 
Deletion at start 
(Head) 
Lecture Notes Data Structures and Algorithms
 
Maryam Amin, Assistant Professor, BIIT 6/10
 
3.3 Node Insertion after a specified location
Following C++ code is used to insert new node after a specified node of a linked list.
void linklist::InsertAtLoc(int n, int d)   {           //display all links 
if (first == NULL)  { 
          cout << “List is empty”; 
          return; 
} 
        int loc=0; 
   link* current = first;             //set ptr to first link 
   while( current != NULL )    {       //quit on last link 
             if (current‐>data == d) { 
                  link* newlink = new link;  
                  newlink‐>data = n; 
                  newlink‐>next = current‐>next; 
                  current‐>next = newlink; 
                  loc=1; 
             } 
             current = current‐>next; 
   } 
   if (loc == 0) 
             cout << “Item not found”; 
   } 
4. Deletion
A new node can be deleted in the following ways.
4.1 Deletion of first node
Following code deletes a node at the start of linked list.
Lecture Notes Data Structures and Algorithms
 
Maryam Amin, Assistant Professor, BIIT 7/10
 
void linklist::DeleteAtStart()  {         //add data item 
   if (first == NULL)  { 
          cout << “Unable to delete List is empty”; 
          return; 
   } 
   link* temp = first;          //save first in a new link 
   first = first‐>next;                 
   temp‐>next = NULL;   
   delete temp;                  
   } 
4.2 Deletion of last Node
Following code deletes a node at the end of linked list.
void linklist::DeleteAtEnd()  {         //add data item 
   if (first == NULL)  { 
          cout << “Unable to delete List is empty”; 
          return; 
   } 
   if (first‐>next == NULL) {      // if there is one node in link list 
          link* temp = first;          //save first in a new link 
          first = first‐>next;                 
          temp‐>next = NULL;   
          delete temp;                  
   } else {                                     // for more than 1 nodes existing in a list 
           
          link* temp=NULL, *current=first;           
          while (current‐>next !=NULL) { 
                    temp=current; 
                    current = current‐>next; 
          } 
          temp‐>next = NULL;   
          delete current;                   
  } 
   } 
4.3 Deletion of a specified Node
Following C++ code is used to delete a specified node in a linked list.
Lecture Notes Data Structures and Algorithms
 
Maryam Amin, Assistant Professor, BIIT 8/10
 
void linklist::DeleteAtLoc(int d)   {           //display all links 
  if (first == NULL)  { 
          cout << “Unable to delete List is empty”; 
          return; 
   }    
          int loc=0; 
     link* temp=NULL, *current=first; 
     while( current != NULL )    {       //quit on last link 
             if (current‐>data == d) { 
                       if (current == first) {     // if desired data is on first node 
         Link *t = first; 
         first = first‐>next; 
                             t‐>next =NULL; 
          delete t; 
                       }  else {    // if desired data is on any other node 
                             temp‐>next = current‐>next; 
                             current‐>next = NULL; 
                             delete current; 
                             current =temp‐>next; 
                             loc=1; 
                       }  
             } 
             temp=current; 
             current = current‐>next; 
       } 
       if (loc == 0) 
                  cout << “Item not found”; 
 } 
5. Count number of Node
Following C++ code is used to count the number of nodes in a linked list.
void linklist::CountNodes()   {           //display all links 
   link* current = first;             //set ptr to first link 
   int n=0; 
   while( current != NULL )    {       //quit on last link 
      n++; 
      current = current‐>next;        //move to next link 
   } 
   cout << “Number of nodes = ” << n; 
   }   
Lecture Notes Data Structures and Algorithms
 
Maryam Amin, Assistant Professor, BIIT 9/10
 
6. Insert a new Node as tenth Node
Following C++ code is used to insert a new node as tenth node in a linked list.
void linklist::Insert10thNodes()   {           //display all links 
   if (first == NULL)  { 
          cout << “List is empty”; 
          return; 
   } 
   link* current = first;             //set ptr to first link 
   int n=0; 
   while( current != NULL )    {       //quit on last link 
         n++; 
         if (n == 9) { 
                  link* newlink = new link;  
                  newlink‐>data = n; 
                  newlink‐>next = current‐>next; 
                  current‐>next = newlink; 
                  break; 
          } 
          current = current‐>next;        //move to next link 
   } 
} 
 
7. Delete tenth Node
Following C++ code is used to delete tenth node in a linked list.
void linklist::Delete10thNodes()   {           //display all links 
   if (first == NULL)  { 
          cout << “List is empty”; 
          return; 
   } 
   link* current = first *temp=NULL;             //set ptr to first link 
   int n=0; 
   while( current != NULL )    {       //quit on last link 
         n++; 
         if (n == 10) { 
                  temp‐>next = current‐>next; 
                  current‐>next = NULL; 
                  delete current; 
                  break; 
          } 
          temp = current; 
          current = current‐>next;        //move to next link 
   } 
} 
Lecture Notes Data Structures and Algorithms
 
Maryam Amin, Assistant Professor, BIIT 10/10
 
Advantages of Link list
Following are the major advantages of link list.
• No contiguous memory is required.
• No wastage of memory
• Efficient insertion and deletion of data elements
Disadvantages of Link list
Following are the major disadvantages of link list.
• It is not easy to access an element directly.
• It is not efficient in searching and sorting

Mais conteúdo relacionado

Mais procurados

computer notes - Linked list
computer notes - Linked listcomputer notes - Linked list
computer notes - Linked listecomputernotes
 
What is Link list? explained with animations
What is Link list? explained with animationsWhat is Link list? explained with animations
What is Link list? explained with animationsPratikNaik41
 
Double Linked List (Algorithm)
Double Linked List (Algorithm)Double Linked List (Algorithm)
Double Linked List (Algorithm)Huba Akhtar
 
Java Linked List Tutorial | Edureka
Java Linked List Tutorial |  EdurekaJava Linked List Tutorial |  Edureka
Java Linked List Tutorial | EdurekaEdureka!
 
Data Structure & Algorithms | Computer Science
Data Structure & Algorithms | Computer ScienceData Structure & Algorithms | Computer Science
Data Structure & Algorithms | Computer ScienceTransweb Global Inc
 
Data structure week y 4
Data structure week y 4Data structure week y 4
Data structure week y 4karmuhtam
 
Data structure &amp; algorithms introduction
Data structure &amp; algorithms introductionData structure &amp; algorithms introduction
Data structure &amp; algorithms introductionSugandh Wafai
 
Chapter 8: tree data structure
Chapter 8:  tree data structureChapter 8:  tree data structure
Chapter 8: tree data structureMahmoud Alfarra
 
Bc0038– data structure using c
Bc0038– data structure using cBc0038– data structure using c
Bc0038– data structure using chayerpa
 
Introduction to data structure ppt
Introduction to data structure pptIntroduction to data structure ppt
Introduction to data structure pptNalinNishant3
 
Towards a New Data Modelling Architecture - Part 1
Towards a New Data Modelling Architecture - Part 1Towards a New Data Modelling Architecture - Part 1
Towards a New Data Modelling Architecture - Part 1JEAN-MICHEL LETENNIER
 
Data structure
Data structureData structure
Data structureMohd Arif
 
Introductiont To Aray,Tree,Stack, Queue
Introductiont To Aray,Tree,Stack, QueueIntroductiont To Aray,Tree,Stack, Queue
Introductiont To Aray,Tree,Stack, QueueGhaffar Khan
 

Mais procurados (20)

computer notes - Linked list
computer notes - Linked listcomputer notes - Linked list
computer notes - Linked list
 
Linked List
Linked ListLinked List
Linked List
 
What is Link list? explained with animations
What is Link list? explained with animationsWhat is Link list? explained with animations
What is Link list? explained with animations
 
Double Linked List (Algorithm)
Double Linked List (Algorithm)Double Linked List (Algorithm)
Double Linked List (Algorithm)
 
Java Linked List Tutorial | Edureka
Java Linked List Tutorial |  EdurekaJava Linked List Tutorial |  Edureka
Java Linked List Tutorial | Edureka
 
Data Structure & Algorithms | Computer Science
Data Structure & Algorithms | Computer ScienceData Structure & Algorithms | Computer Science
Data Structure & Algorithms | Computer Science
 
Data structure week y 4
Data structure week y 4Data structure week y 4
Data structure week y 4
 
Data Structures
Data StructuresData Structures
Data Structures
 
Data structure &amp; algorithms introduction
Data structure &amp; algorithms introductionData structure &amp; algorithms introduction
Data structure &amp; algorithms introduction
 
Chapter 8: tree data structure
Chapter 8:  tree data structureChapter 8:  tree data structure
Chapter 8: tree data structure
 
Semi join
Semi joinSemi join
Semi join
 
Bc0038– data structure using c
Bc0038– data structure using cBc0038– data structure using c
Bc0038– data structure using c
 
AtomiDB Dr Ashis Banerjee reviews
AtomiDB Dr Ashis Banerjee reviewsAtomiDB Dr Ashis Banerjee reviews
AtomiDB Dr Ashis Banerjee reviews
 
Introduction to data structure ppt
Introduction to data structure pptIntroduction to data structure ppt
Introduction to data structure ppt
 
Towards a New Data Modelling Architecture - Part 1
Towards a New Data Modelling Architecture - Part 1Towards a New Data Modelling Architecture - Part 1
Towards a New Data Modelling Architecture - Part 1
 
Latex Tutorial by Dr. M. C. Hanumantharaju
Latex Tutorial by Dr. M. C. HanumantharajuLatex Tutorial by Dr. M. C. Hanumantharaju
Latex Tutorial by Dr. M. C. Hanumantharaju
 
Data structure
Data structureData structure
Data structure
 
Introductiont To Aray,Tree,Stack, Queue
Introductiont To Aray,Tree,Stack, QueueIntroductiont To Aray,Tree,Stack, Queue
Introductiont To Aray,Tree,Stack, Queue
 
Data structure and its types.
Data structure and its types.Data structure and its types.
Data structure and its types.
 
Link list
Link listLink list
Link list
 

Destaque

Integral table
Integral tableIntegral table
Integral tablezzzubair
 
Calculus with analytic geometry swokoWS BYZzzubair
Calculus with analytic geometry swokoWS BYZzzubairCalculus with analytic geometry swokoWS BYZzzubair
Calculus with analytic geometry swokoWS BYZzzubairzzzubair
 
Dsa circular queue
Dsa circular queueDsa circular queue
Dsa circular queuezzzubair
 
Semiconductor Industry - Needs more than Moore's Law
Semiconductor Industry - Needs more than Moore's LawSemiconductor Industry - Needs more than Moore's Law
Semiconductor Industry - Needs more than Moore's LawIBMElectronics
 
A mans right to happiness
A mans right to happinessA mans right to happiness
A mans right to happinessBasil Facey
 
Budd Hopkins - Missing Time
Budd Hopkins - Missing TimeBudd Hopkins - Missing Time
Budd Hopkins - Missing TimeDirkTheDaring11
 
Jenny Randles - The Unexplained - Great Mysteries of the 20th Century
Jenny Randles - The Unexplained - Great Mysteries of the 20th CenturyJenny Randles - The Unexplained - Great Mysteries of the 20th Century
Jenny Randles - The Unexplained - Great Mysteries of the 20th CenturyDirkTheDaring11
 
Jacques Vallee - Anatomy of a Phenomenon
Jacques Vallee - Anatomy of a PhenomenonJacques Vallee - Anatomy of a Phenomenon
Jacques Vallee - Anatomy of a PhenomenonDirkTheDaring11
 
V. evans - successful writing proficiency
V. evans  - successful writing proficiencyV. evans  - successful writing proficiency
V. evans - successful writing proficiencyJavier Eduardo Portela
 
Seismic Analysis of Structures - III
Seismic Analysis of Structures - IIISeismic Analysis of Structures - III
Seismic Analysis of Structures - IIItushardatta
 
Seismic Analysis of Structures - II
Seismic Analysis of Structures - IISeismic Analysis of Structures - II
Seismic Analysis of Structures - IItushardatta
 
Fundamentals of heat exchanger design
Fundamentals of heat exchanger designFundamentals of heat exchanger design
Fundamentals of heat exchanger designJuan Guillermo
 
Workshop: PowerFactory Applications for Power System Analysis. Kasetsart Un...
Workshop: PowerFactory Applications for Power System Analysis. Kasetsart Un...Workshop: PowerFactory Applications for Power System Analysis. Kasetsart Un...
Workshop: PowerFactory Applications for Power System Analysis. Kasetsart Un...Francisco Gonzalez-Longatt
 
Partial differential equations and complex analysis
Partial differential equations and complex analysisPartial differential equations and complex analysis
Partial differential equations and complex analysisSergio Zaina
 
Seismic design-using-structural-dynamics-sk-ghosh
Seismic design-using-structural-dynamics-sk-ghoshSeismic design-using-structural-dynamics-sk-ghosh
Seismic design-using-structural-dynamics-sk-ghoshhamdanraza
 

Destaque (18)

Integral table
Integral tableIntegral table
Integral table
 
DS Q&A
DS Q&ADS Q&A
DS Q&A
 
Calculus with analytic geometry swokoWS BYZzzubair
Calculus with analytic geometry swokoWS BYZzzubairCalculus with analytic geometry swokoWS BYZzzubair
Calculus with analytic geometry swokoWS BYZzzubair
 
Dsa circular queue
Dsa circular queueDsa circular queue
Dsa circular queue
 
Semiconductor Industry - Needs more than Moore's Law
Semiconductor Industry - Needs more than Moore's LawSemiconductor Industry - Needs more than Moore's Law
Semiconductor Industry - Needs more than Moore's Law
 
A mans right to happiness
A mans right to happinessA mans right to happiness
A mans right to happiness
 
18 Puran By R.P.Pandey
18 Puran By R.P.Pandey18 Puran By R.P.Pandey
18 Puran By R.P.Pandey
 
Budd Hopkins - Missing Time
Budd Hopkins - Missing TimeBudd Hopkins - Missing Time
Budd Hopkins - Missing Time
 
Jenny Randles - The Unexplained - Great Mysteries of the 20th Century
Jenny Randles - The Unexplained - Great Mysteries of the 20th CenturyJenny Randles - The Unexplained - Great Mysteries of the 20th Century
Jenny Randles - The Unexplained - Great Mysteries of the 20th Century
 
Jacques Vallee - Anatomy of a Phenomenon
Jacques Vallee - Anatomy of a PhenomenonJacques Vallee - Anatomy of a Phenomenon
Jacques Vallee - Anatomy of a Phenomenon
 
V. evans - successful writing proficiency
V. evans  - successful writing proficiencyV. evans  - successful writing proficiency
V. evans - successful writing proficiency
 
Seismic Analysis of Structures - III
Seismic Analysis of Structures - IIISeismic Analysis of Structures - III
Seismic Analysis of Structures - III
 
Seismic Analysis of Structures - II
Seismic Analysis of Structures - IISeismic Analysis of Structures - II
Seismic Analysis of Structures - II
 
Analytical geometry
Analytical geometryAnalytical geometry
Analytical geometry
 
Fundamentals of heat exchanger design
Fundamentals of heat exchanger designFundamentals of heat exchanger design
Fundamentals of heat exchanger design
 
Workshop: PowerFactory Applications for Power System Analysis. Kasetsart Un...
Workshop: PowerFactory Applications for Power System Analysis. Kasetsart Un...Workshop: PowerFactory Applications for Power System Analysis. Kasetsart Un...
Workshop: PowerFactory Applications for Power System Analysis. Kasetsart Un...
 
Partial differential equations and complex analysis
Partial differential equations and complex analysisPartial differential equations and complex analysis
Partial differential equations and complex analysis
 
Seismic design-using-structural-dynamics-sk-ghosh
Seismic design-using-structural-dynamics-sk-ghoshSeismic design-using-structural-dynamics-sk-ghosh
Seismic design-using-structural-dynamics-sk-ghosh
 

Semelhante a Link list

1.3 Linked List.pptx
1.3 Linked List.pptx1.3 Linked List.pptx
1.3 Linked List.pptxssuserd2f031
 
Data Structures_Linked List
Data Structures_Linked ListData Structures_Linked List
Data Structures_Linked ListThenmozhiK5
 
2 marks- DS using python
2 marks- DS using python2 marks- DS using python
2 marks- DS using pythonLavanyaJ28
 
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...Balwant Gorad
 
linked list in data structure
linked list in data structure linked list in data structure
linked list in data structure shameen khan
 
Lecture4a dynamic data_structure
Lecture4a dynamic data_structureLecture4a dynamic data_structure
Lecture4a dynamic data_structurembadhi barnabas
 
ds-lecture-4-171012041008 (1).pdf
ds-lecture-4-171012041008 (1).pdfds-lecture-4-171012041008 (1).pdf
ds-lecture-4-171012041008 (1).pdfKamranAli649587
 
Notes of bca Question paper for exams and tests
Notes of bca Question paper for exams and testsNotes of bca Question paper for exams and tests
Notes of bca Question paper for exams and testspriyanshukumar97908
 
CS8391-DATA-STRUCTURES.pdf
CS8391-DATA-STRUCTURES.pdfCS8391-DATA-STRUCTURES.pdf
CS8391-DATA-STRUCTURES.pdfraji175286
 
DS Module 03.pdf
DS Module 03.pdfDS Module 03.pdf
DS Module 03.pdfSonaPathak5
 
Unit ii(dsc++)
Unit ii(dsc++)Unit ii(dsc++)
Unit ii(dsc++)Durga Devi
 
Static arrays are structures whose size is fixed at compile time and.pdf
Static arrays are structures whose size is fixed at compile time and.pdfStatic arrays are structures whose size is fixed at compile time and.pdf
Static arrays are structures whose size is fixed at compile time and.pdfanjanacottonmills
 
Deletion from single way linked list and search
Deletion from single way linked list and searchDeletion from single way linked list and search
Deletion from single way linked list and searchEstiak Khan
 

Semelhante a Link list (20)

1.3 Linked List.pptx
1.3 Linked List.pptx1.3 Linked List.pptx
1.3 Linked List.pptx
 
Data Structures_Linked List
Data Structures_Linked ListData Structures_Linked List
Data Structures_Linked List
 
Linked list.docx
Linked list.docxLinked list.docx
Linked list.docx
 
module 3-.pptx
module 3-.pptxmodule 3-.pptx
module 3-.pptx
 
Linkedlists
LinkedlistsLinkedlists
Linkedlists
 
2 marks- DS using python
2 marks- DS using python2 marks- DS using python
2 marks- DS using python
 
csc211_lecture_21.pptx
csc211_lecture_21.pptxcsc211_lecture_21.pptx
csc211_lecture_21.pptx
 
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
 
Linked list (1).pptx
Linked list (1).pptxLinked list (1).pptx
Linked list (1).pptx
 
linked list.pptx
linked list.pptxlinked list.pptx
linked list.pptx
 
linked list in data structure
linked list in data structure linked list in data structure
linked list in data structure
 
Lecture4a dynamic data_structure
Lecture4a dynamic data_structureLecture4a dynamic data_structure
Lecture4a dynamic data_structure
 
ds-lecture-4-171012041008 (1).pdf
ds-lecture-4-171012041008 (1).pdfds-lecture-4-171012041008 (1).pdf
ds-lecture-4-171012041008 (1).pdf
 
Notes of bca Question paper for exams and tests
Notes of bca Question paper for exams and testsNotes of bca Question paper for exams and tests
Notes of bca Question paper for exams and tests
 
CS8391-DATA-STRUCTURES.pdf
CS8391-DATA-STRUCTURES.pdfCS8391-DATA-STRUCTURES.pdf
CS8391-DATA-STRUCTURES.pdf
 
Unit 3 dsa LINKED LIST
Unit 3 dsa LINKED LISTUnit 3 dsa LINKED LIST
Unit 3 dsa LINKED LIST
 
DS Module 03.pdf
DS Module 03.pdfDS Module 03.pdf
DS Module 03.pdf
 
Unit ii(dsc++)
Unit ii(dsc++)Unit ii(dsc++)
Unit ii(dsc++)
 
Static arrays are structures whose size is fixed at compile time and.pdf
Static arrays are structures whose size is fixed at compile time and.pdfStatic arrays are structures whose size is fixed at compile time and.pdf
Static arrays are structures whose size is fixed at compile time and.pdf
 
Deletion from single way linked list and search
Deletion from single way linked list and searchDeletion from single way linked list and search
Deletion from single way linked list and search
 

Último

Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxcallscotland1987
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsKarakKing
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701bronxfugly43
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxAmanpreet Kaur
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 

Último (20)

Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 

Link list

  • 1. Lecture Notes Data Structures and Algorithms   Maryam Amin, Assistant Professor, BIIT 1/10   Lecture 4 to 5   Contents • Linked List • Memory Representation • Operations on Linked List • Traversing • Searching • Insertion o Node Insertion At Start o Node Insertion At End o Node Insertion after a specified location • Deletion o Deletion of first node o Deletion of last Node o Deletion of a specified Node • Count number of Node • Insert a new Node as tenth Node • Delete tenth Node • Advantages of Link list • Disadvantages of Link list Linked List This is most widely used data structure and also very much practical one. Here the elements (nodes) are kept in disjoint memory locations. Each node consists of two parts one for the data and other for address of next node. In array approach which is hardly used but just to clarify the concept. One might be kept for data portion and second for maintaining the appropriate address to next node. As shown in figure below.
  • 2. Lecture Notes Data Structures and Algorithms   Maryam Amin, Assistant Professor, BIIT 2/10   1 W 5 2 S 3 3 I 4 4 F NULL 5 A 2 But this does not reveal the actual meaning of linked list so we go for a pointer approach. Let us consider the operations of insertion and deletion in a sequentially allocated list. Assume that we have an n-element list and that it is required to insert a new element between the second and the third elements. In this case, the last n – 2 elements of the list must be physically moved to make room for the new element. For large-sized lists, which are subjected to many insertions, this insertion approach can be very costly. The same conclusion holds in the case of deletion, since all elements after the deleted element must be moved up so as to use the vacated space caused by the deletion. These two allocation methods (linked and sequential) can be compared with respect to other operations as well. For a search operation in a linked list, we must follow the link from the first node onwards until the desired node is found. This operation is certainly inferior to the computed-address method of locating an element in a sequentially allocated list. If we want to split or join two linked lists, then these operations involve the changing of pointer fields without having to move any nodes. Such is not the case for sequentially allocated counterparts. Clearly, pointers or links consume additional memory. The cost of this additional memory becomes less important as the information contents of a node require more memory. In the above discussion the actual address of a node was used in the link field for illustration purposes. In practice, however, this address may be of no concern (and indeed unknown) to the programmer. Therefore, in the remainder of our discussion of linked structure, the arrow symbol is used exclusively to denote a successor node. The use of pointers is only to specify the relationship of logical adjacency among elements of a linear list. This is an important point to emphasize – the notion of logical adjacency versus physical adjacency. In vector (or sequential) storage, they are the same. In linked storage, they are not. Therefore, we have more flexibility with linked storage.
  • 3. Lecture Notes Data Structures and Algorithms   Maryam Amin, Assistant Professor, BIIT 3/10   Memory Representation A linked list provides a more flexible storage system in that it doesn’t use array at all. Instead, space for each data item is obtained as needed with new, and each item is connected or linked, to the next data item using a pointer. The individual item don’t need to be located in the memory contiguously, the way arrays are; they can be scattered anywhere. struct link   {                                 // node of list     int data;                          //data item   link* next;                      //pointer to next link     };    // class of Linked List  class linklist   {                       //a linked list     private:        link* first;                    //pointer to first link     public:       linklist()                      //no‐argument constructor           { first = NULL; }            //no first link     };  Operations on Linked List Following are the major operations on linked lists. 1. Traversing Following C++ code is used to traverse a linked list. void linklist::display()   {           //display all links     link* current = first;             //set ptr to first link     while( current != NULL )    {       //quit on last link        cout << current‐>data << endl;  //print data        current = current‐>next;        //move to next link        }     }  2. Searching Following C++ code is used to traverse a linked list.
  • 4. Lecture Notes Data Structures and Algorithms   Maryam Amin, Assistant Professor, BIIT 4/10   void linklist::search(int d)   {           //display all links          if (first == NULL) {                  cout << “List is empty”;                  return;          }          int loc=0;     link* current = first;             //set ptr to first link     while( current != NULL )    {       //quit on last link               if (current‐>data == d) {                    cout << “Item found” << endl;                     loc=1;               }               current = current‐>next;     }     if (loc == 0)               cout << “Item not found”;     }  3. Insertion A new node can be inserted in the following ways. 3.1 Node Insertion At Start Following code inserts a new node at the start of linked list. void linklist::InsertAtStart(int d)  {         //add data item     link* newlink = new link;          //make a new link     newlink‐>data = d;                 //give it data     newlink‐>next = first;                                    first = newlink;     }  The given C++ program executes insertion at start. int main()  {   linklist li;       //make linked list   li.InsertAtStart(25);    //add four items to list   li. InsertAtStart (36);   li. InsertAtStart (49);  li.display();  } 
  • 5. Lecture Notes Data Structures and Algorithms   Maryam Amin, Assistant Professor, BIIT 5/10   3.2 Node Insertion At End This approach is simpler it is used for insertion at end. void linklist::InsertAtEnd(int d)  {         //add data item     link* newlink = new link;          //make a new link     newlink‐>data = d;                 //give it data     newlink‐>next = NULL;     if (first == NULL)  {            first = newlink;     }     else {            link *current = first;            while (current‐>next != NULL)                        current = current‐>next;            current‐>next = newlink;                   //now first points to this    }     }  25  NULL 25  NULL36  &25  25  NULL 36  &2549  &36  25  NULL 36  &2549  NUL  Insertion at start  (Head)  Deletion at start  (Head) 
  • 6. Lecture Notes Data Structures and Algorithms   Maryam Amin, Assistant Professor, BIIT 6/10   3.3 Node Insertion after a specified location Following C++ code is used to insert new node after a specified node of a linked list. void linklist::InsertAtLoc(int n, int d)   {           //display all links  if (first == NULL)  {            cout << “List is empty”;            return;  }          int loc=0;     link* current = first;             //set ptr to first link     while( current != NULL )    {       //quit on last link               if (current‐>data == d) {                    link* newlink = new link;                     newlink‐>data = n;                    newlink‐>next = current‐>next;                    current‐>next = newlink;                    loc=1;               }               current = current‐>next;     }     if (loc == 0)               cout << “Item not found”;     }  4. Deletion A new node can be deleted in the following ways. 4.1 Deletion of first node Following code deletes a node at the start of linked list.
  • 7. Lecture Notes Data Structures and Algorithms   Maryam Amin, Assistant Professor, BIIT 7/10   void linklist::DeleteAtStart()  {         //add data item     if (first == NULL)  {            cout << “Unable to delete List is empty”;            return;     }     link* temp = first;          //save first in a new link     first = first‐>next;                     temp‐>next = NULL;       delete temp;                      }  4.2 Deletion of last Node Following code deletes a node at the end of linked list. void linklist::DeleteAtEnd()  {         //add data item     if (first == NULL)  {            cout << “Unable to delete List is empty”;            return;     }     if (first‐>next == NULL) {      // if there is one node in link list            link* temp = first;          //save first in a new link            first = first‐>next;                            temp‐>next = NULL;              delete temp;                      } else {                                     // for more than 1 nodes existing in a list                        link* temp=NULL, *current=first;                      while (current‐>next !=NULL) {                      temp=current;                      current = current‐>next;            }            temp‐>next = NULL;              delete current;                      }     }  4.3 Deletion of a specified Node Following C++ code is used to delete a specified node in a linked list.
  • 8. Lecture Notes Data Structures and Algorithms   Maryam Amin, Assistant Professor, BIIT 8/10   void linklist::DeleteAtLoc(int d)   {           //display all links    if (first == NULL)  {            cout << “Unable to delete List is empty”;            return;     }               int loc=0;       link* temp=NULL, *current=first;       while( current != NULL )    {       //quit on last link               if (current‐>data == d) {                         if (current == first) {     // if desired data is on first node           Link *t = first;           first = first‐>next;                               t‐>next =NULL;            delete t;                         }  else {    // if desired data is on any other node                               temp‐>next = current‐>next;                               current‐>next = NULL;                               delete current;                               current =temp‐>next;                               loc=1;                         }                }               temp=current;               current = current‐>next;         }         if (loc == 0)                    cout << “Item not found”;   }  5. Count number of Node Following C++ code is used to count the number of nodes in a linked list. void linklist::CountNodes()   {           //display all links     link* current = first;             //set ptr to first link     int n=0;     while( current != NULL )    {       //quit on last link        n++;        current = current‐>next;        //move to next link     }     cout << “Number of nodes = ” << n;     }   
  • 9. Lecture Notes Data Structures and Algorithms   Maryam Amin, Assistant Professor, BIIT 9/10   6. Insert a new Node as tenth Node Following C++ code is used to insert a new node as tenth node in a linked list. void linklist::Insert10thNodes()   {           //display all links     if (first == NULL)  {            cout << “List is empty”;            return;     }     link* current = first;             //set ptr to first link     int n=0;     while( current != NULL )    {       //quit on last link           n++;           if (n == 9) {                    link* newlink = new link;                     newlink‐>data = n;                    newlink‐>next = current‐>next;                    current‐>next = newlink;                    break;            }            current = current‐>next;        //move to next link     }  }    7. Delete tenth Node Following C++ code is used to delete tenth node in a linked list. void linklist::Delete10thNodes()   {           //display all links     if (first == NULL)  {            cout << “List is empty”;            return;     }     link* current = first *temp=NULL;             //set ptr to first link     int n=0;     while( current != NULL )    {       //quit on last link           n++;           if (n == 10) {                    temp‐>next = current‐>next;                    current‐>next = NULL;                    delete current;                    break;            }            temp = current;            current = current‐>next;        //move to next link     }  } 
  • 10. Lecture Notes Data Structures and Algorithms   Maryam Amin, Assistant Professor, BIIT 10/10   Advantages of Link list Following are the major advantages of link list. • No contiguous memory is required. • No wastage of memory • Efficient insertion and deletion of data elements Disadvantages of Link list Following are the major disadvantages of link list. • It is not easy to access an element directly. • It is not efficient in searching and sorting