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;
}
200_success
146k22 gold badges190 silver badges478 bronze badges
asked Oct 20, 2017 at 21:17
\$\endgroup\$

1 Answer 1

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.

answered Oct 20, 2017 at 22:21
\$\endgroup\$
1
  • \$\begingroup\$ Why the downvote ? \$\endgroup\$ Commented Oct 20, 2017 at 22:30

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.