我有输出:
节点 1:鲍勃·乔·吉尔 杰夫·吉尔
但我希望它到如果一个名字重复被发送到单链表的前面,所以它会变成
节点 1:吉尔·鲍勃·乔·杰夫
而且我很难实现这一点。
这是我的代码:
string employers[] = {"Jill", "Jeff", "Bob", "Joe", "Monica", "Luis"};
struct node {
node(string name="") {data=name; next=NULL; }
string data;
node *next;
node *prev;
};
class list {
public:
list(int N=0, int value=0);
~list();
void put(int);
friend ostream & operator << (ostream &, const list &);
private:
int N;
node *head;
};
void list::put(int i) {
string employee_name = employers[i];
node * p = new node(g);
node * pp = head;
while (pp - > next) {
pp = pp - > next;
for (int b=6; b<6; b++) {
if (p-> data == names[b]
cout << "found";
}
pp - > next = p;
N++;
}
我遇到的困难是,我如何能够比较链表中的每个条目?我做了一个节点*prev,但我不完全确定如何比较节点。
- 总是写小函数
- 如果一个函数看起来更大,总是分解成更小的函数
- 尽量避免全局数据,如有必要,尝试传递全局值而不是直接对它们进行操作
这是您的解决方案。我添加了一个查找函数并更正了指针管理。
class list {
public:
list():head(NULL), N(0){}
~list(){
//Implementation for cleanup
}
void put(int i){ //left this function so that your code wont break but try removing it
put(employee_names[i]);
}
void put(string name){ //rather than accessing the global data, use the value passed
node* p = new node(name);
p->next=p->prev=NULL;
node* pp = find(name);
if(pp==NULL){
// No match found, append to rear
if(head==NULL)
head=p; //list empty, add first element
else{
node* cur=head;
while(cur->next!=NULL) //Keep looking until a slot is found
cur=cur->next;
cur->next=p;
p->prev=cur;
}
}
else{
//Match found, detach it from its location
node* pPrev = pp->prev;
pPrev->next = pp->next;
pp->next->prev=pPrev;
p->next = head; //append it to the front & adjust pointers
head->prev=p;
}
N++;
}
//MER: finds a matching element and returns the node otherwise returns NULL
node* find(string name){
node *cur=head;
if(cur==NULL) // is it a blank list?
return NULL;
else if(cur->data==head) //is first element the same?
return head;
else // Keep looking until the list ends
while(cur->next!=NULL){
if(cur->data==name)
return cur;
cur=cur->next;
}
return NULL;
}
friend ostream& operator << (ostream& os, const list& mylist);
private:
int N;
node *head;
};
现在有些人可能会告诉你使用 STL 中的列表,永远不要编写自己的代码,因为你无法击败 STL,但对我来说,你实现自己的代码以清楚地了解它在现实中是如何工作的,这是件好事。
如果不是学校作业,我会怎么做。
class EmployerCollection
{
public:
bool AddEmployer(const std::string& name)
{
EmployerList::const_iterator it = std::find(m_employers.begin(), m_employers.end(), name);
if (it != m_employers.end()) // Already exists in list.
{
m_employers.splice(m_employers.begin(), m_employers, it, std::next(it));
return true;
}
m_employers.push_front(name);
return false;
}
private:
typedef std::list<std::string> EmployerList;
EmployerList m_employers;
};
int main()
{
const int NUM_EMPLOYERS = 15;
std::string employers[NUM_EMPLOYERS] = {"Jill", "Jeff", "Jill"};
EmployerCollection c;
for (int i=0; i<NUM_EMPLOYERS; i++)
{
bool duplicate = c.AddEmployer(employers[i]);
printf("Added %s to employer list - duplicate: %s n", employers[i].c_str(), duplicate ? "True" : "False");
}
}