SlideShare a Scribd company logo
1 of 13
Download to read offline
Data Structures: Linked Lists
David Keil 9/04 1
David Keil 9/04 1
Linked lists………...
• Data structures with linked
components
• Operations: insertion, search,
deletion, traversal
• Doubly linked lists
David Keil 9/04 2
Inserting into a sorted collection
• Array or random-access file may require
many steps to open a slot
• Insertion into a chain takes 3 steps
• Assumes knowledge of where to insert
Data Structures: Linked Lists
David Keil 9/04 2
David Keil 9/04 3
A linked list
• Linked lists are chains of nodes
• Their form is more flexible than the cell
structure of the array or random-access file
Header node
Pointer to first node
Links to successor nodes Null link denoting end of list
4 2 9
David Keil 9/04 4
About linked lists
• A second way to implement
collections
• Contain self-referential node
structures
• Operations:
- Insertion - Deletion - Traversal
• Dynamically-allocated node
implementation
Data Structures: Linked Lists
David Keil 9/04 3
David Keil 9/04 5
List-node structure type
…where
• 〈node_references〉 is some data type (e.g.,
subscript or pointer) that refers to a node
• 〈item_type〉 is the data type of the value
stored by a node
struct list_nodes
{
〈item_type〉 data;
〈node_references〉 next;
};
David Keil 9/04 6
Linked lists with dynamically
allocated nodes
3 implementations; “list” item is:
• pointer to first node;
• header node;
• object containing header node
Data Structures: Linked Lists
David Keil 9/04 4
David Keil 9/04 7
Initialize node
1. Assign new value to data member
2. Assign NULL to link member
Append node
1. Step to end of list
2. Link last node to new node
Prepend node
1. Link new node to next of header
2. Link header to new node
David Keil 9/04 8
Linked-list node insertion
Before insertion
1. Allocate new node to
store new value
2. Link new node to
successor
3. Link target to new
node
After insertion
Data Structures: Linked Lists
David Keil 9/04 5
David Keil 9/04 9
Node insertion by prepend (C++)
struct nodes
{
int value;
nodes* next;
};
void lists::prepend(int v)
// Inserts node w/<v> at front.
{
nodes* p_new_node = new nodes;
p_new_node->value = v;
p_new_node->next = header.next;
header.next = p_new_node;
}
class lists
{
public:
prepend(int v);
private:
nodes header;
};
David Keil 9/04 10
List-search (hdr, key)
[Preconditions: hdr is pointer to header node
of linked list, key is value to be found]
i ← next (hdr )
while i ≠ NULL
if value(i ) = key
return i
else
i ← next(i )
return NULL
[Postcondition: Pointer to node containing key
is returned, or NULL if key not found.]
Data Structures: Linked Lists
David Keil 9/04 6
David Keil 9/04 11
Using strcmp to compare strings
struct nodes
{
char name[40];
nodes* next;
};
void main()
{
nodes* p_node = new nodes;
strcpy(p_node->name,”Bob”);
cout << "Search key: ";
char key[40];
cin >> key;
if (strcmp(key,p_node->name) == 0)
cout << "Match" << endl;
}
David Keil 9/04 12
C code for list search
(assumes nodes structure type)
nodes* search_list(nodes hdr,char* key)
/* Returns pointer to node containing
<key>, as value of its member <name>,
in list headed by <hdr>, or NULL if
<key> not found. */
{
nodes* p = hdr.next;
while (p != NULL) {
if (strcmp(p->name,key) == 0)
return p;
else
p = p->next; }
return NULL;
}
Data Structures: Linked Lists
David Keil 9/04 7
David Keil 9/04 13
Linked-list node deletion
(given address of predecessor)
Before deletion process
1. Save address of target node
nodes* target = pred->next;
2. Link predecessor to target's
successor
pred->next = target->next;
3. Deallocate deleted node:
delete target; // C++
David Keil 9/04 14
C code to delete a node
void list_delete_node(nodes* pred)
// Deletes the node after <pred> from list.
{
nodes* target;
/* No action if parm or successor null: */
if (pred == NULL) return;
if (pred->next == NULL) return;
/* Link predecessor of target to
<pred>'s successor: */
target = pred->next;
pred->next = target->next;
/* Deallocated deleted node: */
free(target);
}
Data Structures: Linked Lists
David Keil 9/04 8
David Keil 9/04 15
List traversal to display (C)
void list_display(lists lst)
/* Outputs values in all nodes of <lst>. */
{
/* Iterator is a pointer: */
nodes* p_node = lst.header.next;
/* Loop through list, displaying data: */
while (p_node != NULL)
{
printf("%s ", p_node->value);
p_node = p_node->next;
}
}
David Keil 9/04 16
A linked list of strings (C++)
void linked_lists::prepend(char *s)
// Inserts a node containing value <s> at start of
list.
{
list_nodes *new_node = new list_nodes(s);
new_node->next = header.next;
header.next = new_node;
}
void linked_lists::delete_node(list_nodes *pred)
// Deletes the node following <pred> from list.
{
// Take no action on null parameter:
if (! pred || ! pred->next) return;
// Record address of node to be deleted:
list_nodes *deleted_node = pred->next;
// Link predecessor of deleted node to its successor:
pred->next = deleted_node->next;
delete deleted_node;
} [strlist.cpp]
Data Structures: Linked Lists
David Keil 9/04 9
David Keil 9/04 17
Inserting, deleting with a list of strings
void main()
{
linked_lists list;
char input[80];
cout << endl << endl;
do{
cout << "Enter a string (* to quit): ";
cin >> input;
if (strcmp(input,"*") != 0)
list.prepend(input);
} while (strcmp(input,"*") != 0);
list.display();
list_nodes *p_node = list.first(),
*p_prev = list.get_header();
while (p_node != NULL) {
cout << "Delete " << p_node->get_value() << "?n";
if (toupper(getch()) == 'Y') list.delete_node(p_prev);
elsep_prev = p_node;
p_node = p_node->get_next();
}
cout << "nWhat remains is:n";
list.display();
} [strlist.cpp]
This program
(1) builds a linked
list of strings from
user input,
(2) displays it,
(3) prompts for
deletions, and
(4) displays result.
1
2
3
4
David Keil 9/04 18
A collection class using a linked list
class list_nodes
{
public:
list_nodes() { next = NULL; };
list_nodes(employees e) { emp = e; next = NULL; };
employees get_value() const { return emp; };
list_nodes *get_next() { return next; };
friend class employee_lists;
private:
employees emp;
list_nodes *next;
};
class employee_lists
{
public:
employee_lists() { header.next = NULL; };
bool retrieve(char* file_name);
void prepend(employees e);
void display();
list_nodes *first() { return header.next; };
list_nodes *get_header() { return &header; };
private:
list_nodes header;
};
Node type; instances
allocated on heap
Container class
An instance of employee_lists
is a collection of employees
Data Structures: Linked Lists
David Keil 9/04 10
David Keil 9/04 19
Challenge problem:
• Can you delete a node of a singly
linked list knowing only its
address, not its predecessor’s?
• Hint: You can assign new values
to next member; what other
assignments are possible?
David Keil 9/04 20
Doubly-linked lists
• Each node has link to predecessor as well
as successor
• Advantages:
- Can traverse list backwards and forward
- Can append a node more quickly
- Can delete a node knowing only
its address
• Cost: one extra pointer per node; one extra
step for each node in any operation
• Is DLL faster or slower in any operation?
Data Structures: Linked Lists
David Keil 9/04 11
David Keil 9/04 21
Threaded lists
• Each list node may have a pointer to
a node far ahead in a list; say, 100
nodes ahead
• Thus we can look far ahead without
stepping through all nodes
• This restores some of the benefits of
binary search of arrays
• Maintenance cost for this arrangement
may be high during update operations
David Keil 9/04 22
Pros and cons of linked lists
• Size is limited only by physical
memory
• Expansion is smooth; no copying
of entire collections to insert one
element
• Must visit (n − 1) nodes to access
the nth node
• Less than optimal search time
• Overhead: one or two pointers, one
or two dereferences, per node
Data Structures: Linked Lists
David Keil 9/04 12
David Keil 9/04 23
Linked-list implementations
of collections
• Possible implementations of a node that stores an
item x:
– Class with all data attributes of x, and next
– Class with members x, next
– Generic class with void pointer to x; next
– Class template (for generic linked list)
• Implementations of collection:
– Header node
– Pointer to first node
– Either implementation may use instantiation of
node template as data member
David Keil 9/04 24
Generic linked lists
• If the data member of a node can be
of any type, the collection is general-purpose
• One way to do this:
use void pointers
• Another way, in C++:
class template, e.g., as done in the Standard
Template Library (STL)
• Example: #include <list>
…
list<employees> roster;
Data Structures: Linked Lists
David Keil 9/04 13
David Keil 9/04 25
A linked-list class template
template <class T> class list_nodes
{
public:
list_nodes() { next = NULL; };
dlist_nodes(T v) { value = v; next = NULL; };
T get_value() { return value; };
void set_next(list_nodes<T> *p) { next = p; };
list_nodes<T> *get_next() { return next; };
private:
T value;
list_nodes<T> *next;
};
template <class T> class linked_lists
{
public:
linked_lists() { header.set_next(NULL); };
void append(T v);
void display();
list_nodes<T> *first() { return header.get_next(); };
list_nodes<T> *get_header() { return &header; };
private:
list_nodes<T> header;
}; [listtplt.cpp]
David Keil 9/04 26
2 instantiations of a list template
void main()
{
linked_lists<int> some_numbers;
int input;
do {
cout << "Enter an integer (0 to quit): ";
cin >> input;
if (input != 0)
some_numbers.append(input);
} while (input != 0);
some_numbers.display();
linked_lists<char> word;
char ch;
do {
cout << "Enter a character ("." to quit): ";
cin >> ch;
if (ch != '.')
word.append(ch);
} while (ch != '.');
word.display();
}
list of integers
list of characters
[listtplt.cpp]

More Related Content

What's hot

Data structure lecture 5
Data structure lecture 5Data structure lecture 5
Data structure lecture 5
Kumar
 
Data structure and its types
Data structure and its typesData structure and its types
Data structure and its types
Navtar Sidhu Brar
 
Stacks & Queues
Stacks & QueuesStacks & Queues
Stacks & Queues
tech4us
 
Linked list
Linked listLinked list
Linked list
VONI
 

What's hot (20)

linked list (c#)
 linked list (c#) linked list (c#)
linked list (c#)
 
Linked list
Linked listLinked list
Linked list
 
Linked list
Linked listLinked list
Linked list
 
Linear data structure concepts
Linear data structure conceptsLinear data structure concepts
Linear data structure concepts
 
Data structure lecture 5
Data structure lecture 5Data structure lecture 5
Data structure lecture 5
 
Data Structures - Lecture 7 [Linked List]
Data Structures - Lecture 7 [Linked List]Data Structures - Lecture 7 [Linked List]
Data Structures - Lecture 7 [Linked List]
 
Linked lists 1
Linked lists 1Linked lists 1
Linked lists 1
 
Linked lists
Linked listsLinked lists
Linked lists
 
Data Structure
Data StructureData Structure
Data Structure
 
Data structure and its types
Data structure and its typesData structure and its types
Data structure and its types
 
358 33 powerpoint-slides_8-linked-lists_chapter-8
358 33 powerpoint-slides_8-linked-lists_chapter-8358 33 powerpoint-slides_8-linked-lists_chapter-8
358 33 powerpoint-slides_8-linked-lists_chapter-8
 
linked list in data structure
linked list in data structure linked list in data structure
linked list in data structure
 
Linked lists in Data Structure
Linked lists in Data StructureLinked lists in Data Structure
Linked lists in Data Structure
 
Sql ppt
Sql pptSql ppt
Sql ppt
 
Data structure , stack , queue
Data structure , stack , queueData structure , stack , queue
Data structure , stack , queue
 
Stacks & Queues
Stacks & QueuesStacks & Queues
Stacks & Queues
 
Circular linked list
Circular linked listCircular linked list
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)
 
9 python data structure-2
9 python data structure-29 python data structure-2
9 python data structure-2
 
Linked list
Linked listLinked list
Linked list
 

Similar to Ds lists

C++ please put everthing after you answer it- thanks Complete the stub.docx
C++ please put everthing after you answer it- thanks Complete the stub.docxC++ please put everthing after you answer it- thanks Complete the stub.docx
C++ please put everthing after you answer it- thanks Complete the stub.docx
MatthPYNashd
 
Add these methods to the code - -Create at least three classes such.pdf
Add these methods to the code -   -Create at least three classes such.pdfAdd these methods to the code -   -Create at least three classes such.pdf
Add these methods to the code - -Create at least three classes such.pdf
SebastianRzuHarrisw
 
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
rohit219406
 
Lec3-Linked list.pptx
Lec3-Linked list.pptxLec3-Linked list.pptx
Lec3-Linked list.pptx
FaheemMahmood2
 

Similar to Ds lists (20)

C++ please put everthing after you answer it- thanks Complete the stub.docx
C++ please put everthing after you answer it- thanks Complete the stub.docxC++ please put everthing after you answer it- thanks Complete the stub.docx
C++ please put everthing after you answer it- thanks Complete the stub.docx
 
csc211_lecture_21.pptx
csc211_lecture_21.pptxcsc211_lecture_21.pptx
csc211_lecture_21.pptx
 
UNIT 3a.pptx
UNIT 3a.pptxUNIT 3a.pptx
UNIT 3a.pptx
 
Chapter 5 ds
Chapter 5 dsChapter 5 ds
Chapter 5 ds
 
DLL DATA STRUCT.pptx
DLL DATA STRUCT.pptxDLL DATA STRUCT.pptx
DLL DATA STRUCT.pptx
 
Linked list1.ppt
Linked list1.pptLinked list1.ppt
Linked list1.ppt
 
Add these methods to the code - -Create at least three classes such.pdf
Add these methods to the code -   -Create at least three classes such.pdfAdd these methods to the code -   -Create at least three classes such.pdf
Add these methods to the code - -Create at least three classes such.pdf
 
Linked list.docx
Linked list.docxLinked list.docx
Linked list.docx
 
Linked list
Linked list Linked list
Linked list
 
Lec-4_Linked-List (1).pdf
Lec-4_Linked-List (1).pdfLec-4_Linked-List (1).pdf
Lec-4_Linked-List (1).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
 
Data Structure Lecture 6
Data Structure Lecture 6Data Structure Lecture 6
Data Structure Lecture 6
 
linked list
linked listlinked list
linked list
 
Algo>ADT list & linked list
Algo>ADT list & linked listAlgo>ADT list & linked list
Algo>ADT list & linked list
 
Singly Linked List
Singly Linked ListSingly Linked List
Singly Linked List
 
3.ppt
3.ppt3.ppt
3.ppt
 
3.ppt
3.ppt3.ppt
3.ppt
 
cs201-list-stack-queue.ppt
cs201-list-stack-queue.pptcs201-list-stack-queue.ppt
cs201-list-stack-queue.ppt
 
Lec3-Linked list.pptx
Lec3-Linked list.pptxLec3-Linked list.pptx
Lec3-Linked list.pptx
 
Data structure
Data structureData structure
Data structure
 

Recently uploaded

Top profile Call Girls In Mangalore [ 7014168258 ] Call Me For Genuine Models...
Top profile Call Girls In Mangalore [ 7014168258 ] Call Me For Genuine Models...Top profile Call Girls In Mangalore [ 7014168258 ] Call Me For Genuine Models...
Top profile Call Girls In Mangalore [ 7014168258 ] Call Me For Genuine Models...
gajnagarg
 
一比一原版(PU学位证书)普渡大学毕业证学历认证加急办理
一比一原版(PU学位证书)普渡大学毕业证学历认证加急办理一比一原版(PU学位证书)普渡大学毕业证学历认证加急办理
一比一原版(PU学位证书)普渡大学毕业证学历认证加急办理
ezgenuh
 
Top profile Call Girls In Darbhanga [ 7014168258 ] Call Me For Genuine Models...
Top profile Call Girls In Darbhanga [ 7014168258 ] Call Me For Genuine Models...Top profile Call Girls In Darbhanga [ 7014168258 ] Call Me For Genuine Models...
Top profile Call Girls In Darbhanga [ 7014168258 ] Call Me For Genuine Models...
nirzagarg
 
Abortion pills Dubai (+918133066128) Cytotec 200mg pills UAE Abudhabi
Abortion pills Dubai (+918133066128) Cytotec 200mg pills UAE AbudhabiAbortion pills Dubai (+918133066128) Cytotec 200mg pills UAE Abudhabi
Abortion pills Dubai (+918133066128) Cytotec 200mg pills UAE Abudhabi
Abortion pills in Kuwait Cytotec pills in Kuwait
 
一比一原版(Deakin毕业证书)迪肯大学毕业证成绩单留信学历认证
一比一原版(Deakin毕业证书)迪肯大学毕业证成绩单留信学历认证一比一原版(Deakin毕业证书)迪肯大学毕业证成绩单留信学历认证
一比一原版(Deakin毕业证书)迪肯大学毕业证成绩单留信学历认证
62qaf0hi
 
+97470301568>>buy vape oil,thc oil weed,hash and cannabis oil in qatar doha}}
+97470301568>>buy vape oil,thc oil weed,hash and cannabis oil in qatar doha}}+97470301568>>buy vape oil,thc oil weed,hash and cannabis oil in qatar doha}}
+97470301568>>buy vape oil,thc oil weed,hash and cannabis oil in qatar doha}}
Health
 
John Deere Tractors 5415 Diagnostic Repair Service Manual.pdf
John Deere Tractors 5415 Diagnostic Repair Service Manual.pdfJohn Deere Tractors 5415 Diagnostic Repair Service Manual.pdf
John Deere Tractors 5415 Diagnostic Repair Service Manual.pdf
Excavator
 
如何办理(Waterloo毕业证书)滑铁卢大学毕业证毕业证成绩单原版一比一
如何办理(Waterloo毕业证书)滑铁卢大学毕业证毕业证成绩单原版一比一如何办理(Waterloo毕业证书)滑铁卢大学毕业证毕业证成绩单原版一比一
如何办理(Waterloo毕业证书)滑铁卢大学毕业证毕业证成绩单原版一比一
avy6anjnd
 
在线定制(UBC毕业证书)英属哥伦比亚大学毕业证成绩单留信学历认证原版一比一
在线定制(UBC毕业证书)英属哥伦比亚大学毕业证成绩单留信学历认证原版一比一在线定制(UBC毕业证书)英属哥伦比亚大学毕业证成绩单留信学历认证原版一比一
在线定制(UBC毕业证书)英属哥伦比亚大学毕业证成绩单留信学历认证原版一比一
qh1ao5mm
 

Recently uploaded (20)

Top profile Call Girls In Mangalore [ 7014168258 ] Call Me For Genuine Models...
Top profile Call Girls In Mangalore [ 7014168258 ] Call Me For Genuine Models...Top profile Call Girls In Mangalore [ 7014168258 ] Call Me For Genuine Models...
Top profile Call Girls In Mangalore [ 7014168258 ] Call Me For Genuine Models...
 
Stacey+= Dubai Calls Girls O525547819 Call Girls In Dubai
Stacey+= Dubai Calls Girls O525547819 Call Girls In DubaiStacey+= Dubai Calls Girls O525547819 Call Girls In Dubai
Stacey+= Dubai Calls Girls O525547819 Call Girls In Dubai
 
❤️Panchkula Enjoy 24/7 Escort Service sdf
❤️Panchkula Enjoy 24/7 Escort Service sdf❤️Panchkula Enjoy 24/7 Escort Service sdf
❤️Panchkula Enjoy 24/7 Escort Service sdf
 
一比一原版(PU学位证书)普渡大学毕业证学历认证加急办理
一比一原版(PU学位证书)普渡大学毕业证学历认证加急办理一比一原版(PU学位证书)普渡大学毕业证学历认证加急办理
一比一原版(PU学位证书)普渡大学毕业证学历认证加急办理
 
Top profile Call Girls In Darbhanga [ 7014168258 ] Call Me For Genuine Models...
Top profile Call Girls In Darbhanga [ 7014168258 ] Call Me For Genuine Models...Top profile Call Girls In Darbhanga [ 7014168258 ] Call Me For Genuine Models...
Top profile Call Girls In Darbhanga [ 7014168258 ] Call Me For Genuine Models...
 
T.L.E 5S's (Seiri, Seiton, Seiso, Seiketsu, Shitsuke).pptx
T.L.E 5S's (Seiri, Seiton, Seiso, Seiketsu, Shitsuke).pptxT.L.E 5S's (Seiri, Seiton, Seiso, Seiketsu, Shitsuke).pptx
T.L.E 5S's (Seiri, Seiton, Seiso, Seiketsu, Shitsuke).pptx
 
Muslim Call Girls Churchgate WhatsApp +91-9930687706, Best Service
Muslim Call Girls Churchgate WhatsApp +91-9930687706, Best ServiceMuslim Call Girls Churchgate WhatsApp +91-9930687706, Best Service
Muslim Call Girls Churchgate WhatsApp +91-9930687706, Best Service
 
Abortion pills Dubai (+918133066128) Cytotec 200mg pills UAE Abudhabi
Abortion pills Dubai (+918133066128) Cytotec 200mg pills UAE AbudhabiAbortion pills Dubai (+918133066128) Cytotec 200mg pills UAE Abudhabi
Abortion pills Dubai (+918133066128) Cytotec 200mg pills UAE Abudhabi
 
JOHN DEERE 7200R 7215R 7230R 7260R 7280R TECHNICAL SERVICE PDF MANUAL 2680PGS...
JOHN DEERE 7200R 7215R 7230R 7260R 7280R TECHNICAL SERVICE PDF MANUAL 2680PGS...JOHN DEERE 7200R 7215R 7230R 7260R 7280R TECHNICAL SERVICE PDF MANUAL 2680PGS...
JOHN DEERE 7200R 7215R 7230R 7260R 7280R TECHNICAL SERVICE PDF MANUAL 2680PGS...
 
West Bengal Factories Rules, 1958.bfpptx
West Bengal Factories Rules, 1958.bfpptxWest Bengal Factories Rules, 1958.bfpptx
West Bengal Factories Rules, 1958.bfpptx
 
John deere 7200r 7230R 7260R Problems Repair Manual
John deere 7200r 7230R 7260R Problems Repair ManualJohn deere 7200r 7230R 7260R Problems Repair Manual
John deere 7200r 7230R 7260R Problems Repair Manual
 
一比一原版(Deakin毕业证书)迪肯大学毕业证成绩单留信学历认证
一比一原版(Deakin毕业证书)迪肯大学毕业证成绩单留信学历认证一比一原版(Deakin毕业证书)迪肯大学毕业证成绩单留信学历认证
一比一原版(Deakin毕业证书)迪肯大学毕业证成绩单留信学历认证
 
Bhilai Escorts Service Girl ^ 8250092165, WhatsApp Anytime Bhilai
Bhilai Escorts Service Girl ^ 8250092165, WhatsApp Anytime BhilaiBhilai Escorts Service Girl ^ 8250092165, WhatsApp Anytime Bhilai
Bhilai Escorts Service Girl ^ 8250092165, WhatsApp Anytime Bhilai
 
Is Your Mercedes Benz Trunk Refusing To Close Here's What Might Be Wrong
Is Your Mercedes Benz Trunk Refusing To Close Here's What Might Be WrongIs Your Mercedes Benz Trunk Refusing To Close Here's What Might Be Wrong
Is Your Mercedes Benz Trunk Refusing To Close Here's What Might Be Wrong
 
+97470301568>>buy vape oil,thc oil weed,hash and cannabis oil in qatar doha}}
+97470301568>>buy vape oil,thc oil weed,hash and cannabis oil in qatar doha}}+97470301568>>buy vape oil,thc oil weed,hash and cannabis oil in qatar doha}}
+97470301568>>buy vape oil,thc oil weed,hash and cannabis oil in qatar doha}}
 
John Deere Tractors 5415 Diagnostic Repair Service Manual.pdf
John Deere Tractors 5415 Diagnostic Repair Service Manual.pdfJohn Deere Tractors 5415 Diagnostic Repair Service Manual.pdf
John Deere Tractors 5415 Diagnostic Repair Service Manual.pdf
 
如何办理(Waterloo毕业证书)滑铁卢大学毕业证毕业证成绩单原版一比一
如何办理(Waterloo毕业证书)滑铁卢大学毕业证毕业证成绩单原版一比一如何办理(Waterloo毕业证书)滑铁卢大学毕业证毕业证成绩单原版一比一
如何办理(Waterloo毕业证书)滑铁卢大学毕业证毕业证成绩单原版一比一
 
SEM 922 MOTOR GRADER PARTS LIST, ALL WHEEL DRIVE
SEM 922 MOTOR GRADER PARTS LIST, ALL WHEEL DRIVESEM 922 MOTOR GRADER PARTS LIST, ALL WHEEL DRIVE
SEM 922 MOTOR GRADER PARTS LIST, ALL WHEEL DRIVE
 
在线定制(UBC毕业证书)英属哥伦比亚大学毕业证成绩单留信学历认证原版一比一
在线定制(UBC毕业证书)英属哥伦比亚大学毕业证成绩单留信学历认证原版一比一在线定制(UBC毕业证书)英属哥伦比亚大学毕业证成绩单留信学历认证原版一比一
在线定制(UBC毕业证书)英属哥伦比亚大学毕业证成绩单留信学历认证原版一比一
 
Nangloi Jat Escorts Service Girl ^ 9332606886, WhatsApp Anytime Nangloi Jat
Nangloi Jat Escorts Service Girl ^ 9332606886, WhatsApp Anytime Nangloi JatNangloi Jat Escorts Service Girl ^ 9332606886, WhatsApp Anytime Nangloi Jat
Nangloi Jat Escorts Service Girl ^ 9332606886, WhatsApp Anytime Nangloi Jat
 

Ds lists

  • 1. Data Structures: Linked Lists David Keil 9/04 1 David Keil 9/04 1 Linked lists………... • Data structures with linked components • Operations: insertion, search, deletion, traversal • Doubly linked lists David Keil 9/04 2 Inserting into a sorted collection • Array or random-access file may require many steps to open a slot • Insertion into a chain takes 3 steps • Assumes knowledge of where to insert
  • 2. Data Structures: Linked Lists David Keil 9/04 2 David Keil 9/04 3 A linked list • Linked lists are chains of nodes • Their form is more flexible than the cell structure of the array or random-access file Header node Pointer to first node Links to successor nodes Null link denoting end of list 4 2 9 David Keil 9/04 4 About linked lists • A second way to implement collections • Contain self-referential node structures • Operations: - Insertion - Deletion - Traversal • Dynamically-allocated node implementation
  • 3. Data Structures: Linked Lists David Keil 9/04 3 David Keil 9/04 5 List-node structure type …where • 〈node_references〉 is some data type (e.g., subscript or pointer) that refers to a node • 〈item_type〉 is the data type of the value stored by a node struct list_nodes { 〈item_type〉 data; 〈node_references〉 next; }; David Keil 9/04 6 Linked lists with dynamically allocated nodes 3 implementations; “list” item is: • pointer to first node; • header node; • object containing header node
  • 4. Data Structures: Linked Lists David Keil 9/04 4 David Keil 9/04 7 Initialize node 1. Assign new value to data member 2. Assign NULL to link member Append node 1. Step to end of list 2. Link last node to new node Prepend node 1. Link new node to next of header 2. Link header to new node David Keil 9/04 8 Linked-list node insertion Before insertion 1. Allocate new node to store new value 2. Link new node to successor 3. Link target to new node After insertion
  • 5. Data Structures: Linked Lists David Keil 9/04 5 David Keil 9/04 9 Node insertion by prepend (C++) struct nodes { int value; nodes* next; }; void lists::prepend(int v) // Inserts node w/<v> at front. { nodes* p_new_node = new nodes; p_new_node->value = v; p_new_node->next = header.next; header.next = p_new_node; } class lists { public: prepend(int v); private: nodes header; }; David Keil 9/04 10 List-search (hdr, key) [Preconditions: hdr is pointer to header node of linked list, key is value to be found] i ← next (hdr ) while i ≠ NULL if value(i ) = key return i else i ← next(i ) return NULL [Postcondition: Pointer to node containing key is returned, or NULL if key not found.]
  • 6. Data Structures: Linked Lists David Keil 9/04 6 David Keil 9/04 11 Using strcmp to compare strings struct nodes { char name[40]; nodes* next; }; void main() { nodes* p_node = new nodes; strcpy(p_node->name,”Bob”); cout << "Search key: "; char key[40]; cin >> key; if (strcmp(key,p_node->name) == 0) cout << "Match" << endl; } David Keil 9/04 12 C code for list search (assumes nodes structure type) nodes* search_list(nodes hdr,char* key) /* Returns pointer to node containing <key>, as value of its member <name>, in list headed by <hdr>, or NULL if <key> not found. */ { nodes* p = hdr.next; while (p != NULL) { if (strcmp(p->name,key) == 0) return p; else p = p->next; } return NULL; }
  • 7. Data Structures: Linked Lists David Keil 9/04 7 David Keil 9/04 13 Linked-list node deletion (given address of predecessor) Before deletion process 1. Save address of target node nodes* target = pred->next; 2. Link predecessor to target's successor pred->next = target->next; 3. Deallocate deleted node: delete target; // C++ David Keil 9/04 14 C code to delete a node void list_delete_node(nodes* pred) // Deletes the node after <pred> from list. { nodes* target; /* No action if parm or successor null: */ if (pred == NULL) return; if (pred->next == NULL) return; /* Link predecessor of target to <pred>'s successor: */ target = pred->next; pred->next = target->next; /* Deallocated deleted node: */ free(target); }
  • 8. Data Structures: Linked Lists David Keil 9/04 8 David Keil 9/04 15 List traversal to display (C) void list_display(lists lst) /* Outputs values in all nodes of <lst>. */ { /* Iterator is a pointer: */ nodes* p_node = lst.header.next; /* Loop through list, displaying data: */ while (p_node != NULL) { printf("%s ", p_node->value); p_node = p_node->next; } } David Keil 9/04 16 A linked list of strings (C++) void linked_lists::prepend(char *s) // Inserts a node containing value <s> at start of list. { list_nodes *new_node = new list_nodes(s); new_node->next = header.next; header.next = new_node; } void linked_lists::delete_node(list_nodes *pred) // Deletes the node following <pred> from list. { // Take no action on null parameter: if (! pred || ! pred->next) return; // Record address of node to be deleted: list_nodes *deleted_node = pred->next; // Link predecessor of deleted node to its successor: pred->next = deleted_node->next; delete deleted_node; } [strlist.cpp]
  • 9. Data Structures: Linked Lists David Keil 9/04 9 David Keil 9/04 17 Inserting, deleting with a list of strings void main() { linked_lists list; char input[80]; cout << endl << endl; do{ cout << "Enter a string (* to quit): "; cin >> input; if (strcmp(input,"*") != 0) list.prepend(input); } while (strcmp(input,"*") != 0); list.display(); list_nodes *p_node = list.first(), *p_prev = list.get_header(); while (p_node != NULL) { cout << "Delete " << p_node->get_value() << "?n"; if (toupper(getch()) == 'Y') list.delete_node(p_prev); elsep_prev = p_node; p_node = p_node->get_next(); } cout << "nWhat remains is:n"; list.display(); } [strlist.cpp] This program (1) builds a linked list of strings from user input, (2) displays it, (3) prompts for deletions, and (4) displays result. 1 2 3 4 David Keil 9/04 18 A collection class using a linked list class list_nodes { public: list_nodes() { next = NULL; }; list_nodes(employees e) { emp = e; next = NULL; }; employees get_value() const { return emp; }; list_nodes *get_next() { return next; }; friend class employee_lists; private: employees emp; list_nodes *next; }; class employee_lists { public: employee_lists() { header.next = NULL; }; bool retrieve(char* file_name); void prepend(employees e); void display(); list_nodes *first() { return header.next; }; list_nodes *get_header() { return &header; }; private: list_nodes header; }; Node type; instances allocated on heap Container class An instance of employee_lists is a collection of employees
  • 10. Data Structures: Linked Lists David Keil 9/04 10 David Keil 9/04 19 Challenge problem: • Can you delete a node of a singly linked list knowing only its address, not its predecessor’s? • Hint: You can assign new values to next member; what other assignments are possible? David Keil 9/04 20 Doubly-linked lists • Each node has link to predecessor as well as successor • Advantages: - Can traverse list backwards and forward - Can append a node more quickly - Can delete a node knowing only its address • Cost: one extra pointer per node; one extra step for each node in any operation • Is DLL faster or slower in any operation?
  • 11. Data Structures: Linked Lists David Keil 9/04 11 David Keil 9/04 21 Threaded lists • Each list node may have a pointer to a node far ahead in a list; say, 100 nodes ahead • Thus we can look far ahead without stepping through all nodes • This restores some of the benefits of binary search of arrays • Maintenance cost for this arrangement may be high during update operations David Keil 9/04 22 Pros and cons of linked lists • Size is limited only by physical memory • Expansion is smooth; no copying of entire collections to insert one element • Must visit (n − 1) nodes to access the nth node • Less than optimal search time • Overhead: one or two pointers, one or two dereferences, per node
  • 12. Data Structures: Linked Lists David Keil 9/04 12 David Keil 9/04 23 Linked-list implementations of collections • Possible implementations of a node that stores an item x: – Class with all data attributes of x, and next – Class with members x, next – Generic class with void pointer to x; next – Class template (for generic linked list) • Implementations of collection: – Header node – Pointer to first node – Either implementation may use instantiation of node template as data member David Keil 9/04 24 Generic linked lists • If the data member of a node can be of any type, the collection is general-purpose • One way to do this: use void pointers • Another way, in C++: class template, e.g., as done in the Standard Template Library (STL) • Example: #include <list> … list<employees> roster;
  • 13. Data Structures: Linked Lists David Keil 9/04 13 David Keil 9/04 25 A linked-list class template template <class T> class list_nodes { public: list_nodes() { next = NULL; }; dlist_nodes(T v) { value = v; next = NULL; }; T get_value() { return value; }; void set_next(list_nodes<T> *p) { next = p; }; list_nodes<T> *get_next() { return next; }; private: T value; list_nodes<T> *next; }; template <class T> class linked_lists { public: linked_lists() { header.set_next(NULL); }; void append(T v); void display(); list_nodes<T> *first() { return header.get_next(); }; list_nodes<T> *get_header() { return &header; }; private: list_nodes<T> header; }; [listtplt.cpp] David Keil 9/04 26 2 instantiations of a list template void main() { linked_lists<int> some_numbers; int input; do { cout << "Enter an integer (0 to quit): "; cin >> input; if (input != 0) some_numbers.append(input); } while (input != 0); some_numbers.display(); linked_lists<char> word; char ch; do { cout << "Enter a character ("." to quit): "; cin >> ch; if (ch != '.') word.append(ch); } while (ch != '.'); word.display(); } list of integers list of characters [listtplt.cpp]