64,676
社区成员
发帖
与我相关
我的任务
分享
#ifndef NOTE_H
#define NOTE_H
template <typename T>
class Note{
public:
T nodeValue;
Note<T> *prev;
Note<T> *next;
Note(){
next = this;
prev = this;
}
Note(const T &value):nodeValue(value){
next = this;
prev = this;
}
void writeLinkedList(Note<T> *header, const string& separator);
void erase(Note<T> *curr);
Note<T> *insert(Note<T> *curr, const T &item);
void clear(Note<T> *header);
};
#endif
#include <iostream>
#include <string>
#include "note.h"
using namespace std;
template <typename T>
void Note<T>::writeLinkedList(Note<T> *header, const string& separator = " "){
Note<T> *p = header->next;//header points at the first note, p moves through the list
while(p != header){
cout << p->nodeValue << separator;//we need to change this~
p = p->next;
}
}
template <typename T>
void Note<T>::erase(Note<T> *curr){
//return if current is empty
if(curr->next == curr)
return;
//declare pointers for the predecessor and successor nodes
Note<T> *prevNode = curr->prev;
Note<T> *succNode = curr->next;
//update the pointers for predecessor and successor
prevNode->next = succNode;
succNode->prev = prevNode;
delete curr;//free memory
}
template <typename T>
Note<T>* Note<T>::insert(Note<T> *curr, const T &item){
//declare pointers variable for the new node and the previous node
Note<T> *newNode,*prevNode;
//allocate a default node
newNode = new Note<T>(item);
//make prevNode points to the previous node of current one
prevNode = curr->prev;
//update the newNode's pointers
newNode->prev = prevNode;
newNode->next = curr;
//update the current node and previous node's pointers
//==>points to the new node
prevNode->next = newNode;
curr->prev = newNode;
return newNode;
}
template <typename T>
void Note<T>::clear(Note<T> *header){
while(header->next != header)
erase(header->next);
}
#include <iostream>
#include <string>
#include "note.h" // node class
using namespace std;
int main()
{
// header node for list holding jumbled characters
Note<char> *header = new Note<char>;
string word;
int numWords, i, j;
//randomNumber rnd;
// prompt for the number of words to enter
cout << "How many words will you enter? ";
cin >> numWords;
cout << endl;
for (i = 0; i < numWords; i++)
{
cout << "Word: ";
cin >> word;
// use rnd.random(2) to determine if the char is inserted
// at the front (value = 0) or back (value = 1) of the list
for (j = 0; j < word.length(); j++)
if (rand()%10 == 0)
// insert at the front of the list
insert(header->next, word[j]);
else
// insert at the back of the list
insert(header, word[j]);
// output the word and its jumbled variation
cout << "Word/Jumbled Word: " << word << " ";
writeLinkedList(header);
cout << endl << endl;
// clear the list in preparation for the next word
clear(header);
}
return 0;
}