SlideShare une entreprise Scribd logo
1  sur  24
INDEX ,[object Object]
How does it works?
Pictorial representation of LL
Memory Representation Of LL?
 Common mistakes with LL
 List Initialization
Insertion elements at front and end with examples
Printing a LL
Finding elements in LL
Deleting Elements from LL,[object Object]
How does it work? A linked list works around the idea of pointers, so it is wise to already have a sound knowledge of this subject. The basic principle is that to each element thatyou want to store in the list, you attach either one or two additional variables.these point to the surrounding elements in the list, specifically the next one,andusually the previous one as well. here is the shape of the list in a diagramform, showing elements with both a next and a previous pointer attached:
Linked list with three nodes (A pictorial Representation) List start  : points to first element of list Data : is data of element Next : stores pointer to the next node i.e address of next node List start DATA NEXT DATA NEXT DATA NEXT Pointer of last node will be null always. Node 1 Node 2 Node 3
Linked list with three nodes /* safest to give ListStart an initial legal      value -- NULL indicates empty list */ /* ListStart points to memory allocated at        location 108 */
Sample Linked List Ops (cont) ListStart->data = 5; ListStart->next = NULL; ListStart->next = (EPtr) malloc(sizeof(EStruct)); ListStart->next->data = 9; ListStart->next->next = NULL;
Sample Linked List Ops (cont) ListStart->next->next = (EPtr) malloc(sizeof(EStruct)); ListStart->next->next->data = 6; ListStart->next->next->next = NULL; /* Linked list of 3 elements (count data values):    ListStart points to first element    ListStart->next points to second element    ListStart->next->next points to third element    and ListStart->next->next->next is NULL to       indicate there is no fourth element */
Sample Linked List Ops (cont) /* To eliminate element, start with free operation */ free(ListStart->next->next); /* NOTE: free not enough -- does not change memory    Element still appears to be in list    But C might give memory away in next request    Need to reset the pointer to NULL  */ ListStart->next->next = NULL; /* Element at 132 no longer part of list (safe to    reuse memory) */
Common Mistakes Dereferencing a NULL pointer ListStart = NULL; ListStart->data = 5;        /* ERROR */ Using a freed element free(ListStart->next); ListStart->next->data = 6;  /* PROBLEM */ Using a pointer before set ListStart = (EPtr) malloc(sizeof(EStruct)); ListStart->next->data = 7;  /* ERROR */
List Initialization Certain linked list ops (init, insert, etc.) may change element at start of list (what ListStart points at) to change what ListStart points to could pass a pointer to ListStart (pointer to pointer) alternately, in each such routine, always return a pointer to ListStart and set ListStart to the result of function call (if ListStart doesn’t change it doesn’t hurt) EPtr initList() {   return NULL; } ListStart = initList();
A Helper Function Build a function used whenever a new element is needed (function always sets data, next fields): EPtr newElement(DataType ndata, EPtr nnext) {   EPtr newEl = (EPtr) malloc(sizeof(EStruct));   newEl->data = ndata;   newEl->next = nnext;   return newEl; }
List Insertion (at front) Add new element to list: Make new element’s next pointer point to start of list Make pointer to new element start of list EPtr insertF(EPtr start, DataType dnew) {   return newElement(dnew,start); }  To use, get new value to add (ask user, read from file, whatever), then call insertF: ListStart = insertF(ListStart,NewDataValue);
Insert at Front Example
Insert at Front (Again)
Insert at End Need to find end of list -- use walker (temporary pointer) to “walk” down list EPtr insertE(EPtr start, DataType dnew) {   EPtr last = start;  /* Walker */   if (start == NULL)  /* if list empty, add at */     return newElement(dnew,NULL);     /* start */   else {     while (last->next != NULL) /* stop at */       last = last->next;       /* last item */     last->next = newElement(dnew,NULL);     return start; /* start doesn’t change */   } }
Insert at End Example

Contenu connexe

Tendances (16)

Linklist
LinklistLinklist
Linklist
 
Unit ii(dsc++)
Unit ii(dsc++)Unit ii(dsc++)
Unit ii(dsc++)
 
Linked list
Linked listLinked list
Linked list
 
STACK, LINKED LIST ,AND QUEUE
STACK, LINKED LIST ,AND QUEUESTACK, LINKED LIST ,AND QUEUE
STACK, LINKED LIST ,AND QUEUE
 
Stacks,queues,linked-list
Stacks,queues,linked-listStacks,queues,linked-list
Stacks,queues,linked-list
 
Circular link list.ppt
Circular link list.pptCircular link list.ppt
Circular link list.ppt
 
Data Structure
Data StructureData Structure
Data Structure
 
Python lists
Python listsPython lists
Python lists
 
Unit7 C
Unit7 CUnit7 C
Unit7 C
 
Linked list
Linked listLinked list
Linked list
 
Linear data structure concepts
Linear data structure conceptsLinear data structure concepts
Linear data structure concepts
 
header, circular and two way linked lists
header, circular and two way linked listsheader, circular and two way linked lists
header, circular and two way linked lists
 
Linked List Static and Dynamic Memory Allocation
Linked List Static and Dynamic Memory AllocationLinked List Static and Dynamic Memory Allocation
Linked List Static and Dynamic Memory Allocation
 
Linked lists 1
Linked lists 1Linked lists 1
Linked lists 1
 
List Data Structure
List Data StructureList Data Structure
List Data Structure
 
Lecture2
Lecture2Lecture2
Lecture2
 

Similaire à Linked list1

Homework 05 - Linked Lists (C++)(1) Implement the concepts of a un.pdf
Homework 05 - Linked Lists (C++)(1) Implement the concepts of a un.pdfHomework 05 - Linked Lists (C++)(1) Implement the concepts of a un.pdf
Homework 05 - Linked Lists (C++)(1) Implement the concepts of a un.pdfezzi97
 
Hi,I have added the methods and main class as per your requirement.pdf
Hi,I have added the methods and main class as per your requirement.pdfHi,I have added the methods and main class as per your requirement.pdf
Hi,I have added the methods and main class as per your requirement.pdfannaelctronics
 
please i need help Im writing a program to test the merge sort alg.pdf
please i need help Im writing a program to test the merge sort alg.pdfplease i need help Im writing a program to test the merge sort alg.pdf
please i need help Im writing a program to test the merge sort alg.pdfezonesolutions
 
Class DiagramIn the Assignment #10, you are given three files Ass.pdf
Class DiagramIn the Assignment #10, you are given three files Ass.pdfClass DiagramIn the Assignment #10, you are given three files Ass.pdf
Class DiagramIn the Assignment #10, you are given three files Ass.pdfxlynettalampleyxc
 
import java.util.ArrayList; import java.util.List;public class S.pdf
import java.util.ArrayList; import java.util.List;public class S.pdfimport java.util.ArrayList; import java.util.List;public class S.pdf
import java.util.ArrayList; import java.util.List;public class S.pdfanupamele
 
C++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdf
C++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdfC++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdf
C++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdfcallawaycorb73779
 
JAVA helpNeed bolded lines fixed for it to compile. Thank you!pu.pdf
JAVA helpNeed bolded lines fixed for it to compile. Thank you!pu.pdfJAVA helpNeed bolded lines fixed for it to compile. Thank you!pu.pdf
JAVA helpNeed bolded lines fixed for it to compile. Thank you!pu.pdfsuresh640714
 
Implementation The starter code includes List.java. You should not c.pdf
Implementation The starter code includes List.java. You should not c.pdfImplementation The starter code includes List.java. You should not c.pdf
Implementation The starter code includes List.java. You should not c.pdfmaheshkumar12354
 
2.(Sorted list array implementation)This sorted list ADT discussed .pdf
2.(Sorted list array implementation)This sorted list ADT discussed .pdf2.(Sorted list array implementation)This sorted list ADT discussed .pdf
2.(Sorted list array implementation)This sorted list ADT discussed .pdfarshin9
 
STAGE 2 The Methods 65 points Implement all the methods t.pdf
STAGE 2 The Methods 65 points Implement all the methods t.pdfSTAGE 2 The Methods 65 points Implement all the methods t.pdf
STAGE 2 The Methods 65 points Implement all the methods t.pdfbabitasingh698417
 
please help me in C++Objective Create a singly linked list of num.pdf
please help me in C++Objective Create a singly linked list of num.pdfplease help me in C++Objective Create a singly linked list of num.pdf
please help me in C++Objective Create a singly linked list of num.pdfaminbijal86
 
Write a JAVA LinkedListRec class that has the following methods siz.pdf
Write a JAVA LinkedListRec class that has the following methods siz.pdfWrite a JAVA LinkedListRec class that has the following methods siz.pdf
Write a JAVA LinkedListRec class that has the following methods siz.pdfinfo785431
 
public class MyLinkedListltE extends ComparableltEgtg.pdf
public class MyLinkedListltE extends ComparableltEgtg.pdfpublic class MyLinkedListltE extends ComparableltEgtg.pdf
public class MyLinkedListltE extends ComparableltEgtg.pdfaccostinternational
 
linked list.pptx
linked list.pptxlinked list.pptx
linked list.pptxchin463670
 
The LinkedList1 class implements a Linked list. class.pdf
The LinkedList1 class implements a Linked list. class.pdfThe LinkedList1 class implements a Linked list. class.pdf
The LinkedList1 class implements a Linked list. class.pdfmalavshah9013
 
Write a program to find the number of comparisons using the binary se.docx
 Write a program to find the number of comparisons using the binary se.docx Write a program to find the number of comparisons using the binary se.docx
Write a program to find the number of comparisons using the binary se.docxajoy21
 

Similaire à Linked list1 (20)

Homework 05 - Linked Lists (C++)(1) Implement the concepts of a un.pdf
Homework 05 - Linked Lists (C++)(1) Implement the concepts of a un.pdfHomework 05 - Linked Lists (C++)(1) Implement the concepts of a un.pdf
Homework 05 - Linked Lists (C++)(1) Implement the concepts of a un.pdf
 
Hi,I have added the methods and main class as per your requirement.pdf
Hi,I have added the methods and main class as per your requirement.pdfHi,I have added the methods and main class as per your requirement.pdf
Hi,I have added the methods and main class as per your requirement.pdf
 
please i need help Im writing a program to test the merge sort alg.pdf
please i need help Im writing a program to test the merge sort alg.pdfplease i need help Im writing a program to test the merge sort alg.pdf
please i need help Im writing a program to test the merge sort alg.pdf
 
dynamicList.ppt
dynamicList.pptdynamicList.ppt
dynamicList.ppt
 
Class DiagramIn the Assignment #10, you are given three files Ass.pdf
Class DiagramIn the Assignment #10, you are given three files Ass.pdfClass DiagramIn the Assignment #10, you are given three files Ass.pdf
Class DiagramIn the Assignment #10, you are given three files Ass.pdf
 
import java.util.ArrayList; import java.util.List;public class S.pdf
import java.util.ArrayList; import java.util.List;public class S.pdfimport java.util.ArrayList; import java.util.List;public class S.pdf
import java.util.ArrayList; import java.util.List;public class S.pdf
 
C++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdf
C++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdfC++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdf
C++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdf
 
JAVA helpNeed bolded lines fixed for it to compile. Thank you!pu.pdf
JAVA helpNeed bolded lines fixed for it to compile. Thank you!pu.pdfJAVA helpNeed bolded lines fixed for it to compile. Thank you!pu.pdf
JAVA helpNeed bolded lines fixed for it to compile. Thank you!pu.pdf
 
Implementation The starter code includes List.java. You should not c.pdf
Implementation The starter code includes List.java. You should not c.pdfImplementation The starter code includes List.java. You should not c.pdf
Implementation The starter code includes List.java. You should not c.pdf
 
2.(Sorted list array implementation)This sorted list ADT discussed .pdf
2.(Sorted list array implementation)This sorted list ADT discussed .pdf2.(Sorted list array implementation)This sorted list ADT discussed .pdf
2.(Sorted list array implementation)This sorted list ADT discussed .pdf
 
STAGE 2 The Methods 65 points Implement all the methods t.pdf
STAGE 2 The Methods 65 points Implement all the methods t.pdfSTAGE 2 The Methods 65 points Implement all the methods t.pdf
STAGE 2 The Methods 65 points Implement all the methods t.pdf
 
please help me in C++Objective Create a singly linked list of num.pdf
please help me in C++Objective Create a singly linked list of num.pdfplease help me in C++Objective Create a singly linked list of num.pdf
please help me in C++Objective Create a singly linked list of num.pdf
 
Write a JAVA LinkedListRec class that has the following methods siz.pdf
Write a JAVA LinkedListRec class that has the following methods siz.pdfWrite a JAVA LinkedListRec class that has the following methods siz.pdf
Write a JAVA LinkedListRec class that has the following methods siz.pdf
 
강의자료9
강의자료9강의자료9
강의자료9
 
Adt of lists
Adt of listsAdt of lists
Adt of lists
 
public class MyLinkedListltE extends ComparableltEgtg.pdf
public class MyLinkedListltE extends ComparableltEgtg.pdfpublic class MyLinkedListltE extends ComparableltEgtg.pdf
public class MyLinkedListltE extends ComparableltEgtg.pdf
 
linked list.pptx
linked list.pptxlinked list.pptx
linked list.pptx
 
Ll.pptx
Ll.pptxLl.pptx
Ll.pptx
 
The LinkedList1 class implements a Linked list. class.pdf
The LinkedList1 class implements a Linked list. class.pdfThe LinkedList1 class implements a Linked list. class.pdf
The LinkedList1 class implements a Linked list. class.pdf
 
Write a program to find the number of comparisons using the binary se.docx
 Write a program to find the number of comparisons using the binary se.docx Write a program to find the number of comparisons using the binary se.docx
Write a program to find the number of comparisons using the binary se.docx
 

Dernier

CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...anjaliyadav012327
 
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
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...Pooja Nehwal
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 

Dernier (20)

CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
 
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
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 

Linked list1

  • 1.
  • 2. How does it works?
  • 7. Insertion elements at front and end with examples
  • 10.
  • 11. How does it work? A linked list works around the idea of pointers, so it is wise to already have a sound knowledge of this subject. The basic principle is that to each element thatyou want to store in the list, you attach either one or two additional variables.these point to the surrounding elements in the list, specifically the next one,andusually the previous one as well. here is the shape of the list in a diagramform, showing elements with both a next and a previous pointer attached:
  • 12. Linked list with three nodes (A pictorial Representation) List start : points to first element of list Data : is data of element Next : stores pointer to the next node i.e address of next node List start DATA NEXT DATA NEXT DATA NEXT Pointer of last node will be null always. Node 1 Node 2 Node 3
  • 13. Linked list with three nodes /* safest to give ListStart an initial legal value -- NULL indicates empty list */ /* ListStart points to memory allocated at location 108 */
  • 14. Sample Linked List Ops (cont) ListStart->data = 5; ListStart->next = NULL; ListStart->next = (EPtr) malloc(sizeof(EStruct)); ListStart->next->data = 9; ListStart->next->next = NULL;
  • 15. Sample Linked List Ops (cont) ListStart->next->next = (EPtr) malloc(sizeof(EStruct)); ListStart->next->next->data = 6; ListStart->next->next->next = NULL; /* Linked list of 3 elements (count data values): ListStart points to first element ListStart->next points to second element ListStart->next->next points to third element and ListStart->next->next->next is NULL to indicate there is no fourth element */
  • 16. Sample Linked List Ops (cont) /* To eliminate element, start with free operation */ free(ListStart->next->next); /* NOTE: free not enough -- does not change memory Element still appears to be in list But C might give memory away in next request Need to reset the pointer to NULL */ ListStart->next->next = NULL; /* Element at 132 no longer part of list (safe to reuse memory) */
  • 17. Common Mistakes Dereferencing a NULL pointer ListStart = NULL; ListStart->data = 5; /* ERROR */ Using a freed element free(ListStart->next); ListStart->next->data = 6; /* PROBLEM */ Using a pointer before set ListStart = (EPtr) malloc(sizeof(EStruct)); ListStart->next->data = 7; /* ERROR */
  • 18. List Initialization Certain linked list ops (init, insert, etc.) may change element at start of list (what ListStart points at) to change what ListStart points to could pass a pointer to ListStart (pointer to pointer) alternately, in each such routine, always return a pointer to ListStart and set ListStart to the result of function call (if ListStart doesn’t change it doesn’t hurt) EPtr initList() { return NULL; } ListStart = initList();
  • 19. A Helper Function Build a function used whenever a new element is needed (function always sets data, next fields): EPtr newElement(DataType ndata, EPtr nnext) { EPtr newEl = (EPtr) malloc(sizeof(EStruct)); newEl->data = ndata; newEl->next = nnext; return newEl; }
  • 20. List Insertion (at front) Add new element to list: Make new element’s next pointer point to start of list Make pointer to new element start of list EPtr insertF(EPtr start, DataType dnew) { return newElement(dnew,start); } To use, get new value to add (ask user, read from file, whatever), then call insertF: ListStart = insertF(ListStart,NewDataValue);
  • 21. Insert at Front Example
  • 22. Insert at Front (Again)
  • 23. Insert at End Need to find end of list -- use walker (temporary pointer) to “walk” down list EPtr insertE(EPtr start, DataType dnew) { EPtr last = start; /* Walker */ if (start == NULL) /* if list empty, add at */ return newElement(dnew,NULL); /* start */ else { while (last->next != NULL) /* stop at */ last = last->next; /* last item */ last->next = newElement(dnew,NULL); return start; /* start doesn’t change */ } }
  • 24. Insert at End Example
  • 25. Reading a Group of Elements EPtr readGroup(EPtr start, FILE *instream) { DataType dataitem; while (readDataSucceeds(instream,&dataitem)) /* Add new item at beginning */ start = newElement(dataitem,start); return start; } /* Assume DataType is int: */ int readDataSucceeds(FILE *stream, int *data) { if (fscanf(stream,”%d”,data) == 1) return 1; else return 0; }
  • 26. Reading Group - Add at End EPtr readGroupE(EPtr start, FILE *instream) { EPtr last; DataType data; /* Try to get first new item */ if (!readDataSucceeds(instream,&data)) return start; /* if none, return initial list */ else { /* Add first new item */ if (start == NULL) { /* If list empty, first item is list start */ start = newElement(data,NULL); last = start; }
  • 27. Reading Group - Add at End (cont) else { /* List not initially empty */ last = start; while (last->next != NULL) /* Find end */ last = last->next; /* Add first element at end */ last->next = newElement(data,NULL); last = last->next; } } /* Add remaining elements */ while (readDataSucceeds(instream,&data)) { last->next = newElement(data,NULL); last = last->next; } return start; }
  • 28. Printing a List Use a walker to examine list from first to last void printList(EPtr start) { EPtr temp = start; while (temp != NULL) { printData(temp->data); temp = temp->next; } }
  • 29. Finding an Element in List Return pointer to item (if found) or NULL (not found) EPtr findE(EPtr start, DataType findI) { EPtr findP = start; /* walker */ while ((findP != NULL) && (findP->data is not the same as findI)) findP = findP->next; return findP; }
  • 31. Deletion Code EPtr delete(EPtr start, DataType delI) { EPtr prev = NULL; EPtr curr = start; while ((curr != NULL) && (curr->data is not delI)) { prev = curr; curr = curr->next; } if (curr == NULL) printf(“Item to delete not found”); else { if (prev == NULL) start = start->next; else prev->next = curr->next; free(curr); } return start; }