我正在尝试获取可执行文件中的两个链表,并将它们以交替的位置相互合并。前任。ListOne 1,2,3 和 ListTwo 4,5 新的 ListOne 应该是 1,4,2,5,3。
链表 .h 文件:
class LinkedList
{
private:
struct ListNode
{
string firstName;
string lastName;
long int phoneNumber;
struct ListNode *next;
};
ListNode *head;
public:
LinkedList()
{
head = nullptr;
}
~LinkedList();
void appendNode(string f, string l, long int p);
void displayList();
};
链表 .cpp 文件:
LinkedList::~LinkedList()
{
cout << "LinkList destructor" << endl;
}
void LinkedList::appendNode(string f, string l, long int p)
{
ListNode *newNode;
ListNode *nodePtr;
newNode = new ListNode;
newNode -> firstName = f;
newNode -> lastName = l;
newNode -> phoneNumber = p;
newNode -> next = nullptr;
if (!head)
head = newNode;
else
{
nodePtr = head;
while (nodePtr -> next)
//while nodePtr is pointing to another node
nodePtr = nodePtr -> next;
//move to that node
nodePtr -> next = newNode;
//inset the newNode at the end of the linked list
}
}
void LinkedList::displayList()
{
ListNode *nodePtr;
nodePtr = head;
while(nodePtr)
//while nodePtr is true, meaning there is a node in the list
{
cout << nodePtr -> firstName << endl;
cout << nodePtr -> lastName << endl;
cout << nodePtr -> phoneNumber << endl;
nodePtr = nodePtr -> next;
}
}
可执行文件:
LinkedList ListOne;
LinkedList ListTwo;
ListOne.appendNode("Cate", "Beckem", 7704563454);
ListOne.appendNode("Cabe","Tomas", 7703451523);
ListTwo.appendNode("Mary", "Smith", 4043456543);
ListTwo.appendNode("Mark", "Carter", 4045433454);
我的程序运行完美,包括 displayList 函数。我只是很困惑如何进行合并功能。