SlideShare uma empresa Scribd logo
1 de 33
Linked List
CSE102 – Programming
Fundamentals
Array Implementation
Elements are stored in contiguous array
positions
Array Implementation...
Requires an estimate of the maximum size of the
list
 waste space
Print all element and find an specific number:
 Linear – Traverse whole array
Print i’th Element:
 Constant time - (Example: printf(“%d”,a[i]);
insert and delete: slow
 e.g. insert at position 0 (making a new element)
 requires first pushing the entire array down one spot to
make room
 e.g. delete at position 0
 requires shifting all the elements in the list up one
Pointer Implementation (Linked List)
Ensure that the list is not stored contiguously
 use a linked list
 a series of structures that are not necessarily adjacent in
memory
 Each node contains the element and a pointer to a
structure containing its successor
the last cell’s next link points to NULL
 Compared to the array implementation,
the pointer implementation uses only as much space as is needed for the
elements currently on the list
but requires space for the pointers in each cell
Nodes and Linked Lists
 A linked list is a list that can grow and shrink while
the program is running
 A linked list is constructed using pointers
 A linked list often consists of structs that
contain a pointer variable connecting them to other
dynamic variables
 A linked list can be visualized as items, drawn as
boxes, connected to other items by arrows
10 12 14 end
head
Linked Lists
A linked list is a series of connected nodes
Each node contains at least
 A piece of data (any type)
 Pointer to the next node in the list
Head: pointer to the first node
The last node points to NULL
10 ∅
Head
20 30
10
data pointer
node
Implementing Nodes
Nodes are implemented in C as “struct”
 Example: A structure to store two data items and
a pointer to another node of the same type,
along with a type definition might be:
struct Node
{
int item;
struct Node *next;
};
Self-Referential Structures
A structure may not contain an object of its own type.
struct Node {
int item;
struct Node n; /* Invalid */
};
However, a structure may contain a pointer to the same
type.
struct Node {
int item;
struct Node *pn; /* Valid */
};
The head of a List
The box labeled head, is not a node, but a pointer
variable that points to a node.
Pointer variable head is declared as:
struct Node *head;
10 ∅
head
20 30
Accessing Items in a Node
One way to change the number in the first node from
10 to 12:
head->item = 12;
12 ∅
head
20 30
NULL
The defined constant NULL is used as…
 An end marker for a linked list
 A program can step through a list of nodes by following
the pointers, but when it finds a node containing NULL,
it knows it has come to the end of the list
 The value of a pointer that has nothing to point to
The value of NULL is 0
Any pointer can be assigned the value NULL:
double* there = NULL;
Linked Lists
A linked list is a list of nodes in which each node
has a member variable that is a pointer that
points to the next node in the list
 The first node is called the head
 The pointer variable head, points to the first node
 The pointer named head is not the head of the list…it
points to the head of the list
 The last node contains a pointer set to NULL
Building a Linked List:
Declaring Pointer Variable head
With the node defined and a type definition to
make or code easier to understand, we can
declare the pointer variable head:
struct Node *head;
 head is a pointer variable that will point to the head node
when the node is created
Building a Linked List:
Creating the First Node
To create the first node, the operator new is used
to create a new dynamic variable:
head = (struct Node *)malloc(sizeof(struct Node));
 Now head points to the first, and only, node in the
list
Building a Linked List:
Initializing the Node
Now that head points to a node, we need to
give values to the member variables of the node:
head->item = 10;
head->next = NULL;
 Since this node is the last node, the link is set to NULL
10 ∅
head
Traversing Singly Linked List
void Traverse(struct Node *head)
 Print the data of all the elements
 Print the number of the nodes in the list
 From “main()” function call “Traverse(head)”.
void Traverse(struct Node *head)
{
int num = 0;
struct Node *currNode;
currNode = head;
while (currNode != NULL){
printf(“%d “,currNode->item);
currNode = currNode->next;
num++;
}
printf("Number of nodes in the list: %dn”,num);
}
Traversing Singly Linked List (2)
Output: 12 currnode = head
Num: 1
12 ∅
head
20 30
currnode
Traversing Singly Linked List (2)
Output: 12 20
Num: 2
currnode = currnode->next
12 ∅
head
20 30
currnode
Traversing Singly Linked List (2)
Output: 12 20 30
Num: 3
currnode = currnode->next
12 ∅
head
20 30
currnode
Traversing Singly Linked List (2)
Output: 12 20 30
Num: 3
currnode = NULL at this moment. So function
terminates.
12 ∅
head
20 30
currnode
Inserting a new node
Node* InsertNode(int index, double x)
 Insert a node with data equal to x after the index’th elements. (i.e.,
when index = 0, insert the node as the first element;
 when index = 1, insert the node after the first element, and so
on)
 If the insertion is successful, return the inserted node.
 Otherwise, return NULL.
 (If index is < 0 or > length of the list, the insertion will fail.)
Steps
 Locate index’th element
 Allocate memory for the new node
 Point the new node to its successor
 Point the new node’s predecessor to the new node newNode
index’th
element
Inserting a new node
Possible cases of InsertNode
 Insert into an empty list
 Insert in front
 Insert at back
 Insert in middle
But, in fact, only need to handle two cases
 Insert as the first node (Case 1 and Case 2)
 Insert in the middle or at the end of the list (Case 3 and Case 4)
Inserting a new node
struct Node* InsertNode(int index, double x) {
if (index < 0) return NULL;
int currIndex = 1;
struct Node* currNode = head;
while (currNode!=NULL && index > currIndex) {
currNode = currNode->next;
currIndex++;
}
if (index > 0 && currNode == NULL) return NULL;
Node* newNode = (struct Node *)malloc(sizeof(struct Node));
newNode->data = x;
if (index == 0) {
newNode->next = head;
head = newNode;
}
else {
newNode->next = currNode->next;
currNode->next = newNode;
}
return newNode;
}
Try to locate index’th
node. If it doesn’t exist,
return NULL.
Inserting a new node
struct Node* InsertNode(int index, double x) {
if (index < 0) return NULL;
int currIndex = 1;
struct Node* currNode = head;
while (currNode!=NULL && index > currIndex) {
currNode = currNode->next;
currIndex++;
}
if (index > 0 && currNode == NULL) return NULL;
Node* newNode = (struct Node *)malloc(sizeof(struct Node));
newNode->data = x;
if (index == 0) {
newNode->next = head;
head = newNode;
}
else {
newNode->next = currNode->next;
currNode->next = newNode;
}
return newNode;
}
Create a new node
Inserting a new node
struct Node* InsertNode(int index, double x) {
if (index < 0) return NULL;
int currIndex = 1;
struct Node* currNode = head;
while (currNode!=NULL && index > currIndex) {
currNode = currNode->next;
currIndex++;
}
if (index > 0 && currNode == NULL) return NULL;
Node* newNode = (struct Node *)malloc(sizeof(struct Node));
newNode->data = x;
if (index == 0) {
newNode->next = head;
head = newNode;
}
else {
newNode->next = currNode->next;
currNode->next = newNode;
}
return newNode;
}
Insert as first element
head
newNode
Inserting a new node
struct Node* InsertNode(int index, double x) {
if (index < 0) return NULL;
int currIndex = 1;
struct Node* currNode = head;
while (currNode!=NULL && index > currIndex) {
currNode = currNode->next;
currIndex++;
}
if (index > 0 && currNode == NULL) return NULL;
Node* newNode = (struct Node *)malloc(sizeof(struct Node));
newNode->data = x;
if (index == 0) {
newNode->next = head;
head = newNode;
}
else {
newNode->next = currNode->next;
currNode->next = newNode;
}
return newNode;
}
Insert after currNode
newNode
currNode
Finding a node
int FindNode(double x, struct Node *head)
 Search for a node with the value equal to x in the list.
 If such a node is found, return its position. Otherwise, return
0.
int FindNode(double x, struct Node *head) {
struct Node* currNode = head;
int currIndex = 1;
while (currNode!=NULL && currNode->data != x) {
currNode = currNode->next;
currIndex++;
}
if (currNode!=NULL) return currIndex;
else return 0;
}
Deleting a node
int DeleteNode(double x)
 Delete a node with the value equal to x from the list.
 If such a node is found, return its position. Otherwise, return
0.
Steps
 Find the desirable node (similar to FindNode)
 Release the memory occupied by the found node
 Set the pointer of the predecessor of the found node to the
successor of the found node
Like InsertNode, there are two special cases
 Delete first node
 Delete the node in middle or at the end of the list
Deleting a node
int DeleteNode(double x) {
struct Node* prevNode = NULL;
struct Node* currNode = head;
int currIndex = 1;
while (currNode!=NULL && currNode->data != x) {
prevNode = currNode;
currNode = currNode->next;
currIndex++;
}
if (currNode!=NULL) {
if (prevNode) {
prevNode->next = currNode->next;
delete currNode;
}
else {
head = currNode->next;
delete currNode;
}
return currIndex;
}
return 0;
}
Try to find the node with its
value equal to x
Deleting a node
int DeleteNode(double x) {
struct Node* prevNode = NULL;
struct Node* currNode = head;
int currIndex = 1;
while (currNode!=NULL && currNode->data != x) {
prevNode = currNode;
currNode = currNode->next;
currIndex++;
}
if (currNode!=NULL) {
if (prevNode!=NULL) {
prevNode->next = currNode->next;
free (currNode);
}
else {
head = currNode->next;
delete currNode;
}
return currIndex;
}
return 0;
}
currNodeprevNode
Deleting a node
int DeleteNode(double x) {
struct Node* prevNode = NULL;
struct Node* currNode = head;
int currIndex = 1;
while (currNode!=NULL && currNode->data != x) {
prevNode = currNode;
currNode = currNode->next;
currIndex++;
}
if (currNode!=NULL) {
if (prevNode!=NULL) {
prevNode->next = currNode->next;
free (currNode);
}
else {
head = currNode->next;
free( currNode);
}
return currIndex;
}
return 0;
}
currNodehead
Destroying the list
void DeleteList(struct Node *head)
 Use the DeleteList() function to release all the memory used by
the list.
 Step through the list and delete each node one by one.
void DelteList(struct Node *head) {
struct Node* currNode = head, *nextNode = NULL;
while (currNode != NULL)
{
nextNode = currNode->next;
// destroy the current node
free (currNode);
currNode = nextNode;
}
}
Linked List (Other Operaions)
Find the highest and lowest element from a linked list.
Sort the linked list
Insert a node before (and after) a given number of a linked
list
Reverse the linked list
Print the linked list in reverse order (using (and without
using)recursion)
Delete the last element of a linked list (where you are given
the head of the linked list only)
Find the middle element of a linked list.

Mais conteúdo relacionado

Mais procurados (20)

Linked List - Insertion & Deletion
Linked List - Insertion & DeletionLinked List - Insertion & Deletion
Linked List - Insertion & Deletion
 
Linked lists
Linked listsLinked lists
Linked lists
 
Linear data structure concepts
Linear data structure conceptsLinear data structure concepts
Linear data structure concepts
 
linked list
linked listlinked list
linked list
 
Single linked list
Single linked listSingle linked list
Single linked list
 
C Homework Help
C Homework HelpC Homework Help
C Homework Help
 
Arrays
ArraysArrays
Arrays
 
Multi dimensional array
Multi dimensional arrayMulti dimensional array
Multi dimensional array
 
Linked list
Linked listLinked list
Linked list
 
Data Structures - Lecture 3 [Arrays]
Data Structures - Lecture 3 [Arrays]Data Structures - Lecture 3 [Arrays]
Data Structures - Lecture 3 [Arrays]
 
Array Presentation (EngineerBaBu.com)
Array Presentation (EngineerBaBu.com)Array Presentation (EngineerBaBu.com)
Array Presentation (EngineerBaBu.com)
 
Linked list
Linked listLinked list
Linked list
 
linked list
linked listlinked list
linked list
 
CSE240 Doubly Linked Lists
CSE240 Doubly Linked ListsCSE240 Doubly Linked Lists
CSE240 Doubly Linked Lists
 
1 D Arrays in C++
1 D Arrays in C++1 D Arrays in C++
1 D Arrays in C++
 
Fundamentals of data structures
Fundamentals of data structuresFundamentals of data structures
Fundamentals of data structures
 
Binary tree
Binary treeBinary tree
Binary tree
 
Operations on linked list
Operations on linked listOperations on linked list
Operations on linked list
 
Singly & Circular Linked list
Singly & Circular Linked listSingly & Circular Linked list
Singly & Circular Linked list
 
Data Structure (Dynamic Array and Linked List)
Data Structure (Dynamic Array and Linked List)Data Structure (Dynamic Array and Linked List)
Data Structure (Dynamic Array and Linked List)
 

Destaque

Tema11. imagenes
Tema11. imagenesTema11. imagenes
Tema11. imagenesJGL79
 
Manual de uso correto de equipamentos de proteção individual
Manual de uso correto de equipamentos de proteção individualManual de uso correto de equipamentos de proteção individual
Manual de uso correto de equipamentos de proteção individualIkaika Epi
 
Guias Aha 2005
Guias Aha 2005Guias Aha 2005
Guias Aha 2005reanimador
 
Reclutamiento y selección de peronal recursos
Reclutamiento y selección de peronal recursosReclutamiento y selección de peronal recursos
Reclutamiento y selección de peronal recursosGeovannaPenaloza
 
Tutorial organizacion archivos
Tutorial organizacion archivosTutorial organizacion archivos
Tutorial organizacion archivosconvertidor
 
Revisión sistemática sobre la caries en niños y adolescentes con obesidad y/o...
Revisión sistemática sobre la caries en niños y adolescentes con obesidad y/o...Revisión sistemática sobre la caries en niños y adolescentes con obesidad y/o...
Revisión sistemática sobre la caries en niños y adolescentes con obesidad y/o...Javier González de Dios
 
Bases Curriculares de la Educación Parvularia
Bases Curriculares de la Educación ParvulariaBases Curriculares de la Educación Parvularia
Bases Curriculares de la Educación ParvulariaMaria Isabel Ortiz
 
Lista de libros (en general)
Lista de libros (en general)Lista de libros (en general)
Lista de libros (en general)Oscar Hernandez
 
Fusões de Instituições Bancárias no Brasil
Fusões de Instituições Bancárias no BrasilFusões de Instituições Bancárias no Brasil
Fusões de Instituições Bancárias no BrasilLeonardo Grattarola
 
Treinamento sinalização de segurança
Treinamento sinalização de segurançaTreinamento sinalização de segurança
Treinamento sinalização de segurançaAne Costa
 
Comprendiendo el entorno 2
Comprendiendo el entorno   2Comprendiendo el entorno   2
Comprendiendo el entorno 2Nelson Izaguirre
 
Programa Aprendizaje y Adquisición de Conocimientos
Programa  Aprendizaje y Adquisición de ConocimientosPrograma  Aprendizaje y Adquisición de Conocimientos
Programa Aprendizaje y Adquisición de Conocimientosinvestigacion2020
 
TRIBUNAL SUPERIOR DEL DISTRITO JUDICIAL DE BOGOTA SALA DE JUSTICIA Y PAZ: Sen...
TRIBUNAL SUPERIOR DEL DISTRITO JUDICIAL DE BOGOTA SALA DE JUSTICIA Y PAZ: Sen...TRIBUNAL SUPERIOR DEL DISTRITO JUDICIAL DE BOGOTA SALA DE JUSTICIA Y PAZ: Sen...
TRIBUNAL SUPERIOR DEL DISTRITO JUDICIAL DE BOGOTA SALA DE JUSTICIA Y PAZ: Sen...Poder Ciudadano
 
Tema 4. máquinas y mecanismos (3º eso)
Tema 4. máquinas y mecanismos (3º eso)Tema 4. máquinas y mecanismos (3º eso)
Tema 4. máquinas y mecanismos (3º eso)ambb72
 
Aprimorando o Gerenciamento de Projetos com Mapeamento de Processos BPM
Aprimorando o Gerenciamento de Projetos com Mapeamento de Processos BPMAprimorando o Gerenciamento de Projetos com Mapeamento de Processos BPM
Aprimorando o Gerenciamento de Projetos com Mapeamento de Processos BPMRenato Borges, MBA, PMP,CBPP
 
Modelo de Competencia Perfecta
Modelo de Competencia PerfectaModelo de Competencia Perfecta
Modelo de Competencia Perfectasaladehistoria.net
 

Destaque (20)

Tema11. imagenes
Tema11. imagenesTema11. imagenes
Tema11. imagenes
 
General S
General SGeneral S
General S
 
Manual de uso correto de equipamentos de proteção individual
Manual de uso correto de equipamentos de proteção individualManual de uso correto de equipamentos de proteção individual
Manual de uso correto de equipamentos de proteção individual
 
Guias Aha 2005
Guias Aha 2005Guias Aha 2005
Guias Aha 2005
 
Reclutamiento y selección de peronal recursos
Reclutamiento y selección de peronal recursosReclutamiento y selección de peronal recursos
Reclutamiento y selección de peronal recursos
 
Tutorial organizacion archivos
Tutorial organizacion archivosTutorial organizacion archivos
Tutorial organizacion archivos
 
Revisión sistemática sobre la caries en niños y adolescentes con obesidad y/o...
Revisión sistemática sobre la caries en niños y adolescentes con obesidad y/o...Revisión sistemática sobre la caries en niños y adolescentes con obesidad y/o...
Revisión sistemática sobre la caries en niños y adolescentes con obesidad y/o...
 
Bases Curriculares de la Educación Parvularia
Bases Curriculares de la Educación ParvulariaBases Curriculares de la Educación Parvularia
Bases Curriculares de la Educación Parvularia
 
Procesos de fundición
Procesos de fundiciónProcesos de fundición
Procesos de fundición
 
Lista de libros (en general)
Lista de libros (en general)Lista de libros (en general)
Lista de libros (en general)
 
Fusões de Instituições Bancárias no Brasil
Fusões de Instituições Bancárias no BrasilFusões de Instituições Bancárias no Brasil
Fusões de Instituições Bancárias no Brasil
 
Treinamento sinalização de segurança
Treinamento sinalização de segurançaTreinamento sinalização de segurança
Treinamento sinalização de segurança
 
Comprendiendo el entorno 2
Comprendiendo el entorno   2Comprendiendo el entorno   2
Comprendiendo el entorno 2
 
Programa Aprendizaje y Adquisición de Conocimientos
Programa  Aprendizaje y Adquisición de ConocimientosPrograma  Aprendizaje y Adquisición de Conocimientos
Programa Aprendizaje y Adquisición de Conocimientos
 
Economía Ecológica
Economía EcológicaEconomía Ecológica
Economía Ecológica
 
TRIBUNAL SUPERIOR DEL DISTRITO JUDICIAL DE BOGOTA SALA DE JUSTICIA Y PAZ: Sen...
TRIBUNAL SUPERIOR DEL DISTRITO JUDICIAL DE BOGOTA SALA DE JUSTICIA Y PAZ: Sen...TRIBUNAL SUPERIOR DEL DISTRITO JUDICIAL DE BOGOTA SALA DE JUSTICIA Y PAZ: Sen...
TRIBUNAL SUPERIOR DEL DISTRITO JUDICIAL DE BOGOTA SALA DE JUSTICIA Y PAZ: Sen...
 
Incoterms
IncotermsIncoterms
Incoterms
 
Tema 4. máquinas y mecanismos (3º eso)
Tema 4. máquinas y mecanismos (3º eso)Tema 4. máquinas y mecanismos (3º eso)
Tema 4. máquinas y mecanismos (3º eso)
 
Aprimorando o Gerenciamento de Projetos com Mapeamento de Processos BPM
Aprimorando o Gerenciamento de Projetos com Mapeamento de Processos BPMAprimorando o Gerenciamento de Projetos com Mapeamento de Processos BPM
Aprimorando o Gerenciamento de Projetos com Mapeamento de Processos BPM
 
Modelo de Competencia Perfecta
Modelo de Competencia PerfectaModelo de Competencia Perfecta
Modelo de Competencia Perfecta
 

Semelhante a 17 linkedlist (1)

Array linked list.ppt
Array  linked list.pptArray  linked list.ppt
Array linked list.pptWaf1231
 
Inspect the class declaration for a doubly-linked list node in Node-h-.pdf
Inspect the class declaration for a doubly-linked list node in Node-h-.pdfInspect the class declaration for a doubly-linked list node in Node-h-.pdf
Inspect the class declaration for a doubly-linked list node in Node-h-.pdfvishalateen
 
in C++ , Design a linked list class named IntegerList to hold a seri.pdf
in C++ , Design a linked list class named IntegerList to hold a seri.pdfin C++ , Design a linked list class named IntegerList to hold a seri.pdf
in C++ , Design a linked list class named IntegerList to hold a seri.pdfeyewaregallery
 
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
 
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
 
Mi 103 linked list
Mi 103 linked listMi 103 linked list
Mi 103 linked listAmit Vats
 
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
 
linkedlist-130914084342-phpapp02.pptx
linkedlist-130914084342-phpapp02.pptxlinkedlist-130914084342-phpapp02.pptx
linkedlist-130914084342-phpapp02.pptxMeghaKulkarni27
 

Semelhante a 17 linkedlist (1) (20)

3.linked list
3.linked list3.linked list
3.linked list
 
linked-list.ppt
linked-list.pptlinked-list.ppt
linked-list.ppt
 
Array linked list.ppt
Array  linked list.pptArray  linked list.ppt
Array linked list.ppt
 
Linked list1.ppt
Linked list1.pptLinked list1.ppt
Linked list1.ppt
 
dynamicList.ppt
dynamicList.pptdynamicList.ppt
dynamicList.ppt
 
Inspect the class declaration for a doubly-linked list node in Node-h-.pdf
Inspect the class declaration for a doubly-linked list node in Node-h-.pdfInspect the class declaration for a doubly-linked list node in Node-h-.pdf
Inspect the class declaration for a doubly-linked list node in Node-h-.pdf
 
Unit7 C
Unit7 CUnit7 C
Unit7 C
 
C Exam Help
C Exam Help C Exam Help
C Exam Help
 
Linked list
Linked listLinked list
Linked list
 
in C++ , Design a linked list class named IntegerList to hold a seri.pdf
in C++ , Design a linked list class named IntegerList to hold a seri.pdfin C++ , Design a linked list class named IntegerList to hold a seri.pdf
in C++ , Design a linked list class named IntegerList to hold a seri.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
 
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
 
Linked lists a
Linked lists aLinked lists a
Linked lists a
 
Mi 103 linked list
Mi 103 linked listMi 103 linked list
Mi 103 linked list
 
DSA(1).pptx
DSA(1).pptxDSA(1).pptx
DSA(1).pptx
 
Unit II Data Structure 2hr topic - List - Operations.pptx
Unit II  Data Structure 2hr topic - List - Operations.pptxUnit II  Data Structure 2hr topic - List - Operations.pptx
Unit II Data Structure 2hr topic - List - Operations.pptx
 
Linked List.pptx
Linked List.pptxLinked List.pptx
Linked List.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...
 
Chapter 5 ds
Chapter 5 dsChapter 5 ds
Chapter 5 ds
 
linkedlist-130914084342-phpapp02.pptx
linkedlist-130914084342-phpapp02.pptxlinkedlist-130914084342-phpapp02.pptx
linkedlist-130914084342-phpapp02.pptx
 

Mais de Himadri Sen Gupta (9)

Report of industrial training
Report of industrial trainingReport of industrial training
Report of industrial training
 
Binary search trees (1)
Binary search trees (1)Binary search trees (1)
Binary search trees (1)
 
Graphs
GraphsGraphs
Graphs
 
14 recursion
14 recursion14 recursion
14 recursion
 
Tree
TreeTree
Tree
 
Heap
HeapHeap
Heap
 
Linked lists
Linked listsLinked lists
Linked lists
 
Queue
QueueQueue
Queue
 
1311004
13110041311004
1311004
 

Último

UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingrknatarajan
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Christo Ananth
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSISrknatarajan
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTINGMANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTINGSIVASHANKAR N
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordAsst.prof M.Gokilavani
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduitsrknatarajan
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...ranjana rawat
 
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
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfKamal Acharya
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxupamatechverse
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
(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
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)simmis5
 

Último (20)

UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTINGMANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduits
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
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...
 
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINEDJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
(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...
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 

17 linkedlist (1)

  • 1. Linked List CSE102 – Programming Fundamentals
  • 2. Array Implementation Elements are stored in contiguous array positions
  • 3. Array Implementation... Requires an estimate of the maximum size of the list  waste space Print all element and find an specific number:  Linear – Traverse whole array Print i’th Element:  Constant time - (Example: printf(“%d”,a[i]); insert and delete: slow  e.g. insert at position 0 (making a new element)  requires first pushing the entire array down one spot to make room  e.g. delete at position 0  requires shifting all the elements in the list up one
  • 4. Pointer Implementation (Linked List) Ensure that the list is not stored contiguously  use a linked list  a series of structures that are not necessarily adjacent in memory  Each node contains the element and a pointer to a structure containing its successor the last cell’s next link points to NULL  Compared to the array implementation, the pointer implementation uses only as much space as is needed for the elements currently on the list but requires space for the pointers in each cell
  • 5. Nodes and Linked Lists  A linked list is a list that can grow and shrink while the program is running  A linked list is constructed using pointers  A linked list often consists of structs that contain a pointer variable connecting them to other dynamic variables  A linked list can be visualized as items, drawn as boxes, connected to other items by arrows 10 12 14 end head
  • 6. Linked Lists A linked list is a series of connected nodes Each node contains at least  A piece of data (any type)  Pointer to the next node in the list Head: pointer to the first node The last node points to NULL 10 ∅ Head 20 30 10 data pointer node
  • 7. Implementing Nodes Nodes are implemented in C as “struct”  Example: A structure to store two data items and a pointer to another node of the same type, along with a type definition might be: struct Node { int item; struct Node *next; };
  • 8. Self-Referential Structures A structure may not contain an object of its own type. struct Node { int item; struct Node n; /* Invalid */ }; However, a structure may contain a pointer to the same type. struct Node { int item; struct Node *pn; /* Valid */ };
  • 9. The head of a List The box labeled head, is not a node, but a pointer variable that points to a node. Pointer variable head is declared as: struct Node *head; 10 ∅ head 20 30
  • 10. Accessing Items in a Node One way to change the number in the first node from 10 to 12: head->item = 12; 12 ∅ head 20 30
  • 11. NULL The defined constant NULL is used as…  An end marker for a linked list  A program can step through a list of nodes by following the pointers, but when it finds a node containing NULL, it knows it has come to the end of the list  The value of a pointer that has nothing to point to The value of NULL is 0 Any pointer can be assigned the value NULL: double* there = NULL;
  • 12. Linked Lists A linked list is a list of nodes in which each node has a member variable that is a pointer that points to the next node in the list  The first node is called the head  The pointer variable head, points to the first node  The pointer named head is not the head of the list…it points to the head of the list  The last node contains a pointer set to NULL
  • 13. Building a Linked List: Declaring Pointer Variable head With the node defined and a type definition to make or code easier to understand, we can declare the pointer variable head: struct Node *head;  head is a pointer variable that will point to the head node when the node is created
  • 14. Building a Linked List: Creating the First Node To create the first node, the operator new is used to create a new dynamic variable: head = (struct Node *)malloc(sizeof(struct Node));  Now head points to the first, and only, node in the list
  • 15. Building a Linked List: Initializing the Node Now that head points to a node, we need to give values to the member variables of the node: head->item = 10; head->next = NULL;  Since this node is the last node, the link is set to NULL 10 ∅ head
  • 16. Traversing Singly Linked List void Traverse(struct Node *head)  Print the data of all the elements  Print the number of the nodes in the list  From “main()” function call “Traverse(head)”. void Traverse(struct Node *head) { int num = 0; struct Node *currNode; currNode = head; while (currNode != NULL){ printf(“%d “,currNode->item); currNode = currNode->next; num++; } printf("Number of nodes in the list: %dn”,num); }
  • 17. Traversing Singly Linked List (2) Output: 12 currnode = head Num: 1 12 ∅ head 20 30 currnode
  • 18. Traversing Singly Linked List (2) Output: 12 20 Num: 2 currnode = currnode->next 12 ∅ head 20 30 currnode
  • 19. Traversing Singly Linked List (2) Output: 12 20 30 Num: 3 currnode = currnode->next 12 ∅ head 20 30 currnode
  • 20. Traversing Singly Linked List (2) Output: 12 20 30 Num: 3 currnode = NULL at this moment. So function terminates. 12 ∅ head 20 30 currnode
  • 21. Inserting a new node Node* InsertNode(int index, double x)  Insert a node with data equal to x after the index’th elements. (i.e., when index = 0, insert the node as the first element;  when index = 1, insert the node after the first element, and so on)  If the insertion is successful, return the inserted node.  Otherwise, return NULL.  (If index is < 0 or > length of the list, the insertion will fail.) Steps  Locate index’th element  Allocate memory for the new node  Point the new node to its successor  Point the new node’s predecessor to the new node newNode index’th element
  • 22. Inserting a new node Possible cases of InsertNode  Insert into an empty list  Insert in front  Insert at back  Insert in middle But, in fact, only need to handle two cases  Insert as the first node (Case 1 and Case 2)  Insert in the middle or at the end of the list (Case 3 and Case 4)
  • 23. Inserting a new node struct Node* InsertNode(int index, double x) { if (index < 0) return NULL; int currIndex = 1; struct Node* currNode = head; while (currNode!=NULL && index > currIndex) { currNode = currNode->next; currIndex++; } if (index > 0 && currNode == NULL) return NULL; Node* newNode = (struct Node *)malloc(sizeof(struct Node)); newNode->data = x; if (index == 0) { newNode->next = head; head = newNode; } else { newNode->next = currNode->next; currNode->next = newNode; } return newNode; } Try to locate index’th node. If it doesn’t exist, return NULL.
  • 24. Inserting a new node struct Node* InsertNode(int index, double x) { if (index < 0) return NULL; int currIndex = 1; struct Node* currNode = head; while (currNode!=NULL && index > currIndex) { currNode = currNode->next; currIndex++; } if (index > 0 && currNode == NULL) return NULL; Node* newNode = (struct Node *)malloc(sizeof(struct Node)); newNode->data = x; if (index == 0) { newNode->next = head; head = newNode; } else { newNode->next = currNode->next; currNode->next = newNode; } return newNode; } Create a new node
  • 25. Inserting a new node struct Node* InsertNode(int index, double x) { if (index < 0) return NULL; int currIndex = 1; struct Node* currNode = head; while (currNode!=NULL && index > currIndex) { currNode = currNode->next; currIndex++; } if (index > 0 && currNode == NULL) return NULL; Node* newNode = (struct Node *)malloc(sizeof(struct Node)); newNode->data = x; if (index == 0) { newNode->next = head; head = newNode; } else { newNode->next = currNode->next; currNode->next = newNode; } return newNode; } Insert as first element head newNode
  • 26. Inserting a new node struct Node* InsertNode(int index, double x) { if (index < 0) return NULL; int currIndex = 1; struct Node* currNode = head; while (currNode!=NULL && index > currIndex) { currNode = currNode->next; currIndex++; } if (index > 0 && currNode == NULL) return NULL; Node* newNode = (struct Node *)malloc(sizeof(struct Node)); newNode->data = x; if (index == 0) { newNode->next = head; head = newNode; } else { newNode->next = currNode->next; currNode->next = newNode; } return newNode; } Insert after currNode newNode currNode
  • 27. Finding a node int FindNode(double x, struct Node *head)  Search for a node with the value equal to x in the list.  If such a node is found, return its position. Otherwise, return 0. int FindNode(double x, struct Node *head) { struct Node* currNode = head; int currIndex = 1; while (currNode!=NULL && currNode->data != x) { currNode = currNode->next; currIndex++; } if (currNode!=NULL) return currIndex; else return 0; }
  • 28. Deleting a node int DeleteNode(double x)  Delete a node with the value equal to x from the list.  If such a node is found, return its position. Otherwise, return 0. Steps  Find the desirable node (similar to FindNode)  Release the memory occupied by the found node  Set the pointer of the predecessor of the found node to the successor of the found node Like InsertNode, there are two special cases  Delete first node  Delete the node in middle or at the end of the list
  • 29. Deleting a node int DeleteNode(double x) { struct Node* prevNode = NULL; struct Node* currNode = head; int currIndex = 1; while (currNode!=NULL && currNode->data != x) { prevNode = currNode; currNode = currNode->next; currIndex++; } if (currNode!=NULL) { if (prevNode) { prevNode->next = currNode->next; delete currNode; } else { head = currNode->next; delete currNode; } return currIndex; } return 0; } Try to find the node with its value equal to x
  • 30. Deleting a node int DeleteNode(double x) { struct Node* prevNode = NULL; struct Node* currNode = head; int currIndex = 1; while (currNode!=NULL && currNode->data != x) { prevNode = currNode; currNode = currNode->next; currIndex++; } if (currNode!=NULL) { if (prevNode!=NULL) { prevNode->next = currNode->next; free (currNode); } else { head = currNode->next; delete currNode; } return currIndex; } return 0; } currNodeprevNode
  • 31. Deleting a node int DeleteNode(double x) { struct Node* prevNode = NULL; struct Node* currNode = head; int currIndex = 1; while (currNode!=NULL && currNode->data != x) { prevNode = currNode; currNode = currNode->next; currIndex++; } if (currNode!=NULL) { if (prevNode!=NULL) { prevNode->next = currNode->next; free (currNode); } else { head = currNode->next; free( currNode); } return currIndex; } return 0; } currNodehead
  • 32. Destroying the list void DeleteList(struct Node *head)  Use the DeleteList() function to release all the memory used by the list.  Step through the list and delete each node one by one. void DelteList(struct Node *head) { struct Node* currNode = head, *nextNode = NULL; while (currNode != NULL) { nextNode = currNode->next; // destroy the current node free (currNode); currNode = nextNode; } }
  • 33. Linked List (Other Operaions) Find the highest and lowest element from a linked list. Sort the linked list Insert a node before (and after) a given number of a linked list Reverse the linked list Print the linked list in reverse order (using (and without using)recursion) Delete the last element of a linked list (where you are given the head of the linked list only) Find the middle element of a linked list.