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

LinkedList of int nodes in C++

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

Problem

I'm new to C++ programming. I'm experienced in Java and its OOP paradigm.
This code works well. I just need to make sure whether it's correct in terms of C++ programming standard.

main.cpp

#include 
#include "ListNode.h"
#include "LinkedList.h"

using namespace std;

int main(void) {

    LinkedList l;
    ListNode a(10);
    ListNode b(5);
    ListNode c(3);
    l.addFirst(a);
    l.addFirst(b);
    l.addLast(c);

    bool empty = l.isEmpty();

    cout << l.listSize() << endl;

    cout << empty << endl;

    system("PAUSE");
    return 0;
}


LinkedList.h

#pragma once
#include "ListNode.h"

class LinkedList
{
public:
    LinkedList();
    ~LinkedList();
    void addFirst(ListNode &node);
    void addLast(ListNode &node);
    bool isEmpty();
    int listSize();

private:
    ListNode *head;
    ListNode *tail;
    int size;
};


LinkedList.cpp

#include "LinkedList.h"

LinkedList::LinkedList()
{
    head = new ListNode();
    tail = new ListNode();
}

LinkedList::~LinkedList()
{
}

void LinkedList::addFirst(ListNode & node)
{
    if (isEmpty())
    {
        *head = node;
        *tail = node;
        size = 1;
    }
    else {
        node.setNext(*head);
        head->setPrev(node);
        *head = node;
        size++;
    }
}

void LinkedList::addLast(ListNode & node)
{
    if (isEmpty())
    {
        *tail = node;
        *head = node;
        size = 1;
    }
    else
    {
        tail->setNext(node);
        node.setPrev(*tail);
        *tail = node;
        size++;
    }
}

bool LinkedList::isEmpty()
{
    return size == 0;
}

int LinkedList::listSize()
{
    return size;
}


ListNode.h

```
#pragma once
class ListNode
{
public:
ListNode();
ListNode(int val);
~ListNode();

inline void setPrev(ListNode &node) { *prev = node; }
inline ListNode *getPrev() { return prev; }
inline void setNext(ListNode &node) { *next = node; }
inline ListNode *getNext() { return next; }
inline void setValue(int val) { val

Solution

Two things:

  • You need to use a lot of consts.



Example:

void setNext(ListNode &node)

    void setNext(const ListNode &node)


  • You call to new in some places of your code but never call to delete

Code Snippets

void setNext(ListNode &node)

    void setNext(const ListNode &node)

Context

StackExchange Code Review Q#149741, answer score: 5

Revisions (0)

No revisions yet.