我有输出:
node 1: Bob Joe Jill Jeff Jill
但我希望它在重复的名字被发送到单向链表的前面,所以它会变成
node 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,但我不完全确定如何比较这些节点。
- 总是写小函数
- 如果一个函数看起来更大,总是分解成更小的函数
- 尽量避免使用全局数据,必要时尽量传递全局值而不是直接对其进行操作
这是您的解决方案。我添加了一个查找功能并更正了指针管理。
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 中的列表 n 永远不要编写自己的代码,因为您无法击败 STL,但对我来说,实现自己的代码以清楚地了解它在其中的工作原理是件好事现实。