Skip to main content

Singly Linked List

Implementation of a singly linked list class

// SLList.cpp
// implementation of singly linked list
#include <iostream>
using namespace std;

class ListNode {
public:
int data;
ListNode* next;
ListNode(int d) {
data = d;
next = NULL;
}
};

class SLList {
ListNode* sentinel;
int size;
public:
SLList() {
sentinel = new ListNode(63);
};
void append(int data) {
ListNode* current;
current = sentinel;
while (current->next) {
current = current->next;
}
size += 1;
current->next = new ListNode(data);
};
void print() {
ListNode* current;
current = sentinel->next;
while (current) {
cout << current->data << " ";
current = current->next;
}
cout << endl;
};
void deleteNode(int pos) {
ListNode* current;
current = sentinel;
if (pos > size - 1) {
return;
}
for (int i = 0; i < pos; i++) {
current = current->next;
}
if (current->next) {
current->next = current->next->next;
} else {
current->next = NULL;
}
};
};

// usage
int main() {
SLList list;
list.append(5);
list.deleteNode(0);
list.print();
return 0;
}