2
\$\begingroup\$

I wrote a small algorithm in C++ that rearranges linked list based on pivot. But my concern is that code is ugly with all the pointers and ->. I don't think that modern C++ is written like this. How do I improve this code?

#include <iostream>
#include <string>

class Node {
public:
    int value;
    Node* next;
    Node(int n) {
        value = n;
        next = NULL;
    };

    Node* partition(int around, Node* node) {
        Node* head = node;
        Node* tail = node;
        Node* temp = node;

        while (temp != NULL) {
            Node *next = temp->next;
            if (temp->value < around) {
                temp->next = head;
                head = temp;
            } else {
                tail->next = temp;
                tail = temp;
            }
            temp = next;
        }

        tail->next = NULL;
        return head;
    }

    void printList() {
        Node *node = this;
        std::cout << "List: ";
        while (node) {
            std::cout << node->value << " ";
            node = node->next;
        }
        std::cout << std::endl;
    }
};

int main() {

    Node n0 = Node(6);
    Node n1 = Node(5);
    Node n2 = Node(4);
    Node n3 = Node(3);
    Node n4 = Node(2);
    Node n5 = Node(1);

    n0.next = &n1;
    n1.next = &n2;
    n2.next = &n3;
    n3.next = &n4;
    n4.next = &n5;

    n0.printList();
    Node *result = n0.partition(3, &n0);
    result->printList();

    return 0;
}
\$\endgroup\$
2
\$\begingroup\$

Those -> are really a standard.

You could change them to the * dereference operator but the parenthesis apocalypse it requires to make it works in larger expressions will bother you more than everything. In a small implementation like this one it's do-able though.

Or, you may want to write your stuff in an immutable fashion. Meaning you don't use pointers and just use return values and arguments to functions to pass values. Without modifying them (as variables) so you never have to use pointers.

\$\endgroup\$
1
  • \$\begingroup\$ Why the downvote ? \$\endgroup\$ – user8786753 Oct 20 '17 at 22:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.