当前位置: 动力学知识库 > 问答 > 编程问答 >

string - Return a pointer to a sorted list; linked list in C++

问题描述:

i want this function sortPair to take 2 Node pointers and return a pointer to a list of the 2 elements sorted alphabetically. The code below is what I have so far. If someone could let me know where I went wrong, that would be great.

 struct Node{

string val;

Node* next;

};

Node* sortPair (Node* p1, Node* p2){

//Assert that neither pointer is null

assert(p1!=NULL);

assert(p2!=NULL);

Node* head=NULL;

Node* current=NULL;

Node* last = NULL;

current = new Node();

if(p1-> val >p2-> val) //If p1->val comes before p2->val in the alphabet

{

current->val = p1->val;

head = current;

last = current;

current = new Node();

current -> val = p2->val;

last = current;

last ->next = NULL;

}

else

{

current->val = p2->val;

head = current;

last = current;

current = new Node();

current -> val = p1->val;

last = current;

last ->next = NULL;

}

return head;

}

网友答案:

A linked list is just a series of nodes that are linked by each element having a pointer to the next one.

From your code, it seems like you do not want to make a list of the two nodes, but rather insert a node into a list that already exists.

If all you want to do is to make a linked list of the two nodes that are there, then set the one with the lower or higher value, depending on how you sort them, to point at the other one. For example, if you are sorting from smallest to biggest, set the smallest node's next pointer to point to the bigger one and return the pointer of the smallest one.

If you want to add one of the nodes into a list of nodes, then you must loop through the list until you find one that is larger or smaller than the node you want to insert. I recommend using a while loop.

If you want to merge two lists, then you must make a new loop that inserts each element of one list into the other list.

There is no need to make a new node for any of this, just use the ones you have and change the next pointers.

Hope this helps.

分享给朋友:
您可能感兴趣的文章:
随机阅读: