HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcppMinor

Example of a singly linked list in C++

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
examplelistlinkedsingly

Problem

I wrote this implementation of a singly linked list but I don't find my code enough simple and compact. Could you help me to simplify it?

Includes

#include 
#include 


Structure of data elements

template
struct Link {
    T val;
    Link* next;
};


Class of singly linked list

```
template
class SLinkedList {

public:

//Default constructor
SLinkedList(): first_(NULL), size_(0) {}

//Copy constructor
SLinkedList(const SLinkedList& other) {
if(other.first_) {
first_ = new Link();
size_ = other.size_;
Link* index1 = first_;
Link* index2 = other.first_;
index1->val = index2->val;

while(index2->next) {
index1->next = new Link();
index1 = index1->next;
index2 = index2->next;
index1->val = index2->val;
}
}
else first_ = other.first_;
}

//Destructor
~SLinkedList() {
clear();
}

//Index operator
T& operator[](int i) {
if(first_) {
if(i size_)
throw std::out_of_range("index out of range!!!");

if(i == 0) return first_->val;

Link* index = first_;
for(int it=0; itnext;
return index->val;
}
else throw std::out_of_range("empty list!!!");
}

//Access first element
T& front() {
return first_->val;
}

//Access last element
T& back() {
return end()->val;
}

//Add an element at the begining
void push_front(const T& value) {
Link* temp = new Link();
temp->val = value;
temp->next = first_;
first_ = temp;
size_++;
}

//Add an element at the end
void push_back(const T& value) {
Link* temp = new Link();
temp->val = value;
temp->next = NULL;
size_++;

if(!first_) first_ = temp;
else {

Solution

Since you're using c++, you should probably be using nullptr rather than NULL.

You also have a few edge case bugs:

  • clear doesn't reset first_ after it has emptied the list (you're currently only calling clear in your code just before you reassign first_ or destroy the class which is why you're probably getting away with it).



  • pop_back doesn't reset first_ if there's only one item in the list.

Context

StackExchange Code Review Q#142179, answer score: 4

Revisions (0)

No revisions yet.