Upload
others
View
14
Download
0
Embed Size (px)
Citation preview
Marco AlvarezDepartment of Computer Science and Statistics
University of Rhode Island
CSC 212: Data Structures and AbstractionsLinked Lists
Spring 2019
!2
!3https://aidemos.microsoft.com/
Linked Lists
Arrays‣ Think about making insertions efficiently
✓ what is the cost? (rear, front, middle)
‣ Think about making deletions efficiently✓ what is the cost?
!5
3 1 2 4 10 20 22
ptr
Linked Lists‣ Collections of sequential elements stored at non-contiguous locations
‣ Nodes are connected by links✓ every node keeps a pointer to the next node
‣ Can grow and shrink dynamically
!6
Singly Linked List
!7
1 7 3 5
Head Tail
NULL pointer
data data data data
next next next next
Operations on Linked Lists‣ Linked lists are just collections of sequential data
✓ can insert 1 or more elements- front, end, by index, by value (sorted lists)
✓ can delete 1 or more elements- front, end, by index, by value
✓ can search for a specific element✓ can get an element at a given index✓ can traverse the list
- visit all nodes and perform an operation (e.g. print or destroy)
✓ …
!8
Implementing a Singly Linked List
Linked lists in C++‣ Need to review:
✓ C++ Classes✓ Pointers
- NULL pointers
✓ Dynamic Memory Allocation- new- delete
✓ Pointers and Classes- dot notation (.)- arrow notation (->)
!10
!11
5class Node { private: int data; Node *next; // add private data/methods // ... public: Node(int d); ~Node(); // add public methods // ... friend class List; }; !12
class List { private: Node *head; Node *tail; // all private data/methods // ... public: List(); ~List(); // all public methods // ... };
1 7 3 5
Head Tail
NULL pointer
Append (insert at end)
!13
Prepend (insert at front)
!14
Insert by index
!15
Delete at front
!16
Delete at end
!17
Delete by value
!18
Delete by index
!19
Get
!20
Search
!21
Destroy (freeing a linked list)
!22
Traversing a linked list‣ Using a for loop
‣ Using recursion
!23
Circular Singly Linked List
!24
1 7 3 5
Head Tail
73 1
Doubly Linked List
!25
Head Tail
NULL pointerNULL pointer
873 1
Circular Doubly Linked List
!26
Head Tail
8