【发布时间】:2016-01-28 12:10:44
【问题描述】:
我正在尝试获取可执行文件中的两个链表,并将它们以交替的位置相互合并。前任。 ListOne 1,2,3 和 ListTwo 4,5 新的 ListOne 应该是 1,4,2,5,3。
LinkedList .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();
};
LinkedList .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 函数。我只是很困惑如何进行合并功能。
【问题讨论】:
-
您只需向
LinkedList添加一个方法,该方法采用LinkedList并遍历传入的参数并为传入LinkedList中的每个节点调用appendNode跨度> -
@Gread.And.Powerful.Oz 哦,我明白你在说什么。我会试试看
-
请使用相关代码编辑您的帖子,以便我更简洁准确地回答您的问题。
-
@Gread.And.Powerful.Oz 你认为你可以为那个方法改正一些伪代码,因为我画了几个空白
-
查看上述
appendNode方法中的while循环。首先,方法签名:merge(LinkedList &b)然后ListNode* node = b.head; while (node) { appendNode(node); node = node->next; }--- 请注意复制node,否则您将链接两个列表。
标签: c++ class linked-list c++14 alternating