0% found this document useful (0 votes)
12 views17 pages

Chapter 5 - Lists - Full

This document discusses lists as a fundamental data structure, emphasizing their ordered nature and the importance of position. It covers the implementation of linked lists, detailing operations such as insertion, deletion, and traversal, along with their time complexities. Additionally, it presents an abstract data type (ADT) for lists and provides a sample implementation of a singly linked list in C++.

Uploaded by

hadytarabay12
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views17 pages

Chapter 5 - Lists - Full

This document discusses lists as a fundamental data structure, emphasizing their ordered nature and the importance of position. It covers the implementation of linked lists, detailing operations such as insertion, deletion, and traversal, along with their time complexities. Additionally, it presents an abstract data type (ADT) for lists and provides a sample implementation of a singly linked list in C++.

Uploaded by

hadytarabay12
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Data Structures and Algorithms

Chapter 5 – Lists

Dr. Georges Badr

1
Lists
•A finite, ordered sequence of elements (ordered means, each element has
a position)
•Most important concept is that of position
• First element, second element, etc.
•Notation: <a0, a1, …, an-1>
•Each list of elements has a data type, and we define a set of operations for it.
• ADT → list can be used for integers, characters, employees, etc.
•A list is defined by
• Front / Head: the start of the list (position 0)
• Back / Tail: the last element in the list (position n-1)

CSC315 - DR MIREILLE MAKARY 2


Lists
•Lists should be able to grow and shrink dynamically
•Ability to insert and delete from anywhere
•We will define the operations that can be applied to the list through
the definition of the ADT for a list.
•We define the ADT List an abstract class:
• An abstract class is one whose member functions are all declared to be “pure virtual”
as indicated by the “=0” notation at the end of the member function declarations
• Cannot be instantiated
• Virtual methods must be overridden in the derived classes.
• We don’t specify how operations are implemented

3
Linked lists implementation

14
Linked Lists implementation
•The linked list uses dynamic memory allocation, that is, it allocates memory
for new list elements as needed.
•A linked list is made up of a series of objects, called the nodes of the list.
•Space grows with number of elements.
•Every element requires overhead.

15
Linked Lists implementation
 Insertion at the head: O(1) – we keep a pointer to head
 Insertion at the end: O(1) if we keep a pointer to tail
 Insertion at any position O(n), go to position and just adjust the pointers.
 Deletion from the head: O(1) – we keep a pointer to head
 Deletion from the end: O(n) – loop till the last element
 Deletion at any position O(n) – search for element or position and just adjust
pointers
 Search could be linear O(n)
▪ If sorted we could also apply binary search but it might not be very efficient since we don’t keep
positions.

16
The linked list operations (as defined in the std API in C++)
 front(): Returns the value of the first element in the list.
 back(): Returns the value of the last element in the list.
 begin(): Returns an iterator pointing to the first element of the list.
 end(): Returns an iterator pointing to the last element
 empty(): Returns whether the list is empty (true) or not(false).
 size(): Returns the number of elements in the list
 push_front(g): Adds a new element ‘g’ at the beginning of the list.
 push_back(g): Adds a new element ‘g’ at the end of the list.
 Insert(g,p): Inserts a new element ‘g’ at the position ‘p’
 pop_front(): removes the first element of the list
 pop_back(): removes the last element of the list
 remove (g): removes all elements equal to a ‘g’ and returns the number of occurrences removed
 clear(): removes all elements from the list, making its size = 0
 print(): prints the content of the list
17
Singly linked-List Implementation
List.h //returns the number of elements in the list
virtual int size() = 0;
#include<iostream>
using namespace std; //adds a new element at the beginning of the list
virtual void push_front(const T& element) = 0;
template<typename T>
//adds a new element at the end of the list
virtual void push_back(const T& element) = 0;
class List
//inserts new element in the list before the element at a
{
specified position
//returns the value of the first element in the list
virtual void insert (const T &element, int pos) = 0;
virtual const T &front() = 0;
//removes the first element of the list
//return the value of the last element in the list
virtual T pop_front() = 0;
virtual const T &back() = 0;

//returns an iterator pointing to the first element in the list //removes the last element of the list
virtual Node <T>* begin() = 0; virtual T pop_back() = 0;

//return an iterator pointing to the theoretical last element //removes all elements equal to a given element and
virtual Node<T>* end() = 0; returns the number of occurrences removed
virtual int remove (const T& element) = 0;
//return whether the list is empty
virtual bool empty() = 0; //removes all elements from the list, making its size = 0
virtual void clear() = 0;

//prints the content of the list


virtual void print() = 0;
};
18
Singly linked-List Implementation
Node.h
template <typename T>

class Node
{
private:
T data;
Node<T>* next;

public:
//constructors
Node(){}
Node( T data, Node<T>* next = NULL)
{
this->data = data;
this->next = next;
}

//getters
T getData() {return data;}
Node<T>*getNext() {return next;}

//setters
void setData (T data){this->data = data;}
void setNext (Node<T>* next){this->next=next;}

//print
void print(){cout<<data<<" ";}

//destructor
//~Node() { delete this;}
19
};
Singly linked-List Implementation
SinglyLinkedList.h ~SinglyLinkedList(){
clear();
}
#include <iostream>
using namespace std; const T &front()
{
#include "List.h" // if (empty()) // if(head == nullptr)
// exit(-1); // the whole application will stop
// better to check if empty in the main or use exception
handling: throw exception
template <typename T>
// else
return head->getData();
class SinglyLinkedList: public List<T> }
{ // also works with T front() {return head->getData();}
private:
Node<T>* head; // back() -O(1)
Node<T>* tail = nullptr; const T &back()
int sz = 0; { // double check in main if empty
return tail->getData();
public: }
SinglyLinkedList (Node<T>* h = nullptr)
// empty -O(1)
{
bool empty()
head = h;
{
if (head!=nullptr) return head == nullptr; // return sz==0;
{ }
tail = head;
sz = 1; // end() -O(1)
} Node<T> *end()
} {
return tail; // if empty --> return nullptr
} 20
Singly linked-List Implementation
// begin() -O(1)
Node<T> *begin(){
return head; // if empty --> return nullptr
}

// push_front(g) Adds g at the beginning


void push_front(const T &g)
{ // O(1)
Node<T> *n = new Node<T>(g, head); // create node
head = n;
if (tail == nullptr) // first element
tail = head;
sz++;
cout << g << " is added to the front\n";
}

// push_back(g) Adds ‘g’ at the end.


void push_back(const T &g) // O(1)
{ // create node
Node<T> *n = new Node<T>(g);
if (empty())
head = n;
else
{
tail->setNext(n);
}
tail = n;
sz++;
cout << g << " is added at the end\n";
} 21
Singly linked-List Implementation
// insert() Inserts new elements in the list before the element at a specified position.
void insert(const T &g, int pos)
{ // O(n)
if (pos < 0 || pos > sz){
cout << pos << " is invalid, should be between 0 and " << sz << endl;
return;
}
if (pos == sz){
push_back(g);
return;
}
if (pos == 0){
push_front(g);
return;
}
cout << g << " was inserted at pos " << pos << endl;
Node<T> *n = new Node<T>(g);
Node<T> *cur = head;
for(int i = 1 ; i<=pos; i++){
cur = cur->getNext();
}
// change pointers
n->setNext(cur->getNext());
cur->setNext(n);
sz++;
}
22
Singly linked-List Implementation
void print() {
//O(n)
//check if empty
if (empty()) {
cout << "\nList is empty\n";
return;
}
cout << "\nList elements are:";
Node<T>* cur = head;
while (cur != nullptr) {
cout << cur->getData() << " ";
cur = cur->getNext();
}
}

//deletion functions: pop_front, pop_back and remove


T pop_front() { //O(1)
//check if empty in the main
Node<T>* cur = head;
//take a copy of the value
T temp = cur->getData(); //T temp = front();
head = head->getNext();
delete cur;
if (head == nullptr) //we only had 1 element
tail = nullptr;
sz--;
return temp;
}
23
Singly linked-List Implementation
//pop_back remove last element //removes all ‘element’ and returns the number of occurrences removed
T pop_back() { //O(n) int remove(const T& element) {
if (empty())
//check if empty in the main
return -1;

T temp = tail->getData(); //T temp = back(); int count = 0;


Node<T>* cur = head; Node<T>* cur = head, * prev = nullptr;
//if we only had 1 element, empty the list while (cur != nullptr) {
if (sz == 1) { if (cur->getData() == element) {
if (prev == nullptr) { //if it's the first element
head = tail = nullptr; head = head->getNext();
delete cur; delete cur;
return temp; cur = head;
} }
else {
prev->setNext(cur -> getNext());
//move till the node prior to the tail
delete cur;
while (cur->getNext() != tail) { cur = prev->getNext();
cur = cur->getNext(); }
} //increment the count when you delete
cur->setNext(nullptr); count++;
delete tail; }
else { //if it's not the element, move the 2 pointers to the next
tail = cur; prev = cur;
sz--; cur = cur->getNext();
return temp; }
} }
//check if the tail was removed
if (prev->getNext() == nullptr)
tail = prev;

//reduce the size by count


sz -= count;
return count;
} 24
Singly linked-List Implementation
//clear function void interchange() {
void clear() { if (head == nullptr || head->getNext() == nullptr) {
if (empty()) return;
return; }
Node<T>* cur = head;
while (cur != nullptr) { Node<T>* prev = nullptr;
head = head->getNext(); Node<T>* curr = head;
delete cur; Node<T>* next = head->getNext();
cur = head; head = next;
}
sz = 0; while (curr != nullptr && next != nullptr) {
tail = nullptr; curr->setNext(next->getNext());
} next->setNext(curr);

if (prev != nullptr) {
//size function prev->setNext(next);
int size() { }
return sz;
} prev = curr;
curr = curr->getNext();
if (curr != nullptr) {
next = curr->getNext();
}
}
tail = prev;
}

}; //close the class


25
Singly linked-List Implementation
SLLMain.cpp
#include"SinglyLinkedList.h"
#include<iostream>
using namespace std;

int main()
{
SinglyLinkedList <int> ssl;
ssl.insert(0,0);

ssl.push_front(1);
ssl.push_front(7);
ssl.push_front(1);
ssl.push_front(8);
ssl.push_front(3);

ssl.print(); output
return 0;
}

26
To do: Doubly Linked Lists

CSC315 - DR MIREILLE MAKARY 27

You might also like