我有外线:
节点1:Bob Joe Jill Jeff Jill
但我希望它能在某个名称重复的地方发送到单链表的前面,所以它会成为
节点1:Jill Bob Joe Jeff
我无法实现它。
这是我的代码:
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,但我不完全确定如何比较节点。
答案 0 :(得分:0)
这是您的解决方案。我添加了一个find函数并更正了指针管理。
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,但对我而言,你正在实施自己的代码来清楚地了解它是如何工作的,这很好。现实。
答案 1 :(得分:0)
如果不是学校作业,我就是这样做的。
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");
}
}