Click here to Skip to main content
15,887,485 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i wrote code that types out names of people and how many times the name has appeared(votes), i'm struggling on how to get my list sorted.

What I have tried:

C++
#include <iostream>
using namespace std;
struct Node {
  string name;
  int count;
  Node * next;
};
int main() {
  string s;
  void printlist(Node * );  
  void sortedinserted(Node * );
  Node * head, * cur, * prev, * tmp;
  head = cur = prev = tmp = NULL;
  while (1) {
    getline(cin, s);
    if (s.length() == 0) {
      break;

    }
    tmp = new Node;
    tmp -> name = s;
    tmp -> count = 1;
    tmp -> next = NULL;

    if (head == NULL)
      head = tmp;
    else {
      prev = NULL;
      cur = head;
    }
    cur = head;
    while (cur) {
      if (cur -> name == s) {
        cur -> count += 1;
        break;
      } else {
        prev = cur;
        cur = cur -> next;
      }
    }
    if (cur == NULL) {
      prev -> next = tmp;
    }
  }
  printlist(head);
  sortedinsert(head);
  return 0;
}
void sortedinsert(Node * head){
Node * cur = head ;
Node * tmp;
Node * prev = NULL;
while(cur){
if(cur->name > tmp->name){
tmp->next=cur;
prev->next=tmp;
break;
}
void printlist(Node * head) {
  Node * cur = head;
  while (cur) {
    cout << cur -> name << cur -> count << endl;
    cur = cur -> next;
  }
}
Posted
Updated 9-Dec-20 8:08am
v2
Comments
CPallini 9-Dec-20 4:11am    
Why don't you use STL containers?
Richard MacCutchan 9-Dec-20 4:43am    
Create an array containing the pointers to each node. You can then sort the array into whatever order you need.

1 solution

You better structure your code better. These internal functions are bad style. Use some own classes and some STL containers like vector.

I guess that you may visit some C++ tutorial to enhance your knowledge. Spending that time is worth it and will improve your code.

tip: write some code with test data to debug more easily.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900