选举投票小练习
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
| #include <iostream> #include <string> using namespace std;
class Node { public: Node(){} Node(string name){candidateName = name;next=NULL;} void setNext(Node *p){next=p;} void setTicketNumber(int n){ticketNumber=n;} void setCandidateName(string name){candidateName = name;} int getTicketNumber(){return ticketNumber;} string getCandidateName(){return candidateName;} Node *getNext(){return next;} private: int ticketNumber; string candidateName; Node *next; };
class Linklist { public: Linklist(){head=NULL;} Linklist(string name){ head = new Node(name); } void addAtEnd(string name); void visitAllNode(); int voteCandidate(string name);
private: Node *head; }; void Linklist::addAtEnd(string name) { Node *p=head; if(head==NULL){ head = new Node(name);} else { while(p->getNext()!=NULL) { p= p->getNext(); } p->setNext(new Node(name)); } }
void Linklist::visitAllNode() { Node *p; p=head; if(p==NULL){cout<<"空链表!"<<endl;} else { while(p->getNext()!=NULL) { p=p->getNext(); cout<< p->getCandidateName() << " " << p->getTicketNumber() << endl; } cout << head->getTicketNumber() << endl; } }
int Linklist::voteCandidate(string name) { Node *p; p = head; if (p==NULL) { return 0; } else { while (p->getNext()!=NULL && p->getCandidateName()!= name) { p=p->getNext(); } if(p->getCandidateName() == name) { int currentTicketNumber = p->getTicketNumber(); p->setTicketNumber(currentTicketNumber+1); } else { head->setTicketNumber(head->getTicketNumber()+1); } } return p->getTicketNumber(); }
int main(int argc, const char * argv[]) { Linklist *pl = NULL; pl = new Linklist("error"); string line; while (cin>>line) { if (line == "getVoteResult") { pl->visitAllNode(); return 0; } else if(line == "addCandidate") { cin >> line; string candidateName = line; pl->addAtEnd(candidateName); } else if(line == "vote") { cin >> line; string candidateName = line; pl->voteCandidate(line); } } return 0; }
|