Linked-List in C++ Programming
Linked-List in C++ Programming
Programming II
Linked List data structure
A quick review
About the implementation of
linked list data structure
Lecture overview
❑ Overall lectures
C++
Outline
❑ A Brief of Outline
▪ In a linked list, each element is linked with each other. struct Element
struct List
data: integer
Elements in a linked list are accessed sequentially. n: integer
*next: Element
*head: Element
▪ Each element contains End struct
*tail: Element
✓ Data End struct
✓ A link (pointer)
✓ to its next element (successor)
✓ and/or to its previous element (predecessor)
▪ In linked list, the first element is head and the last element is tail
Array Vs. Linked List
❑ Pros and Con
▪ A double linked list is a linked list that has both links to successor and predecessor.
Data
A pointer points to the next
TAIL
element (successor)
myList1
▪ A single or double linked list can be called a circular linked list when the last
element (tail) points to the first element (head).
Data
Address of next element
List operation
❑ Operation with a list
head null
tmp new(size(Element))
tmp→ data 10
tmp→ next head
head tmp
tmp head
head head → next
free(tmp)
Create a list
❑ A function to create an empty list
End function
Insertion
❑ Insert an element to the beginning of the list Old list
Procedure insert_be(*ls: List, d: data_type) Tail
var *E: Element
1 E new(size(Element))
E→data d
2
E→next ls→head
3 ls→head E
if(ls→n ==0) then Tail
4 ls→tail E Tail
end if
5 ls→n ls→n + 1
End procedure
while(tmp!=NULL) do
write(tmp→data)
tmp tmp→next
end while
End procedure
Implementation
Let’s take a look on another functions
Head NULL
Head
NULL
1 2
Tail
ls→tail→next E
ls→tail E
ls→n ls→n + 1
end if
End procedure
How it works … ?
How to search data in linked list
Tail
Head
NULL
Search
❑ Search for data in list
Steps to search element in list
1. …
2. …
3. …
4. …
How it works … ?
How to delete data from linked list
Tail
Before
Head
NULL
NULL
Head
After
Delete the first element (delete beginning)
Head Tail
Head
tmp
NULL
tmp
How it works … ?
Q&A
More about delete
Head
NULL
After NULL
Delete the last element
while(ls→n > 0) do
delete_be(ls)
end while
End procedure
How it works … ?