示例: 链表A:1-> 2-> 3 链表B:4-> 5-> 6C++ - 插入链表(A)到在位置另一链表(B)N
我的任务是创建一个函数,它将列表B传递到列表A中的任何给定位置(n)。例如:在“2”= 1-> 4-> 5-> 6-> 2-> 3(输出)之后。
我真的不知道,如何做到这一点,所以我用:
//功能是发现在列表中的号码,并获取节点的地址。
Node* List::find(int i)
{
for (start();!end();next())
if(current->num==i) return current;
return NULL;
};
//功能,在列表中的位置n放置自由期望的数字;
示例cin >> i; // i = ;
1-> 2-> - >所需的数字 - > ...
Node* List::addAfter(int pos, int num)
{
Node* p = NULL; i
current = find(pos);
if (current != NULL)
{
p = new Node(num);
p->next = current->next;
current->next = p;
}
if (last == current) last = p;
current = p;
return p;
}
两个东西的作品,但只是作为:
cout << "After which number?" << endl;
cin >> i; // **2**
l.addAfter(i, 1); // Before: 2->3->4 After: 2->1->3->4
l.print();
这工作完全!但如果我有两个列表 - l1(2-> 3-> 4和l2 6-> 7) 如何使用此功能将两者放在一起?
节点*名单:: addAfter(INT POS,我必须要通过L2 VALUES这里) 我怎能舍弃这个功能L2值作为参数? 有没有更好的方法来做到这一点?我会很感激任何帮助。
整个代码:
#include <iostream>
using namespace std;
class Node
{
public:
int num;
Node *next;
Node (int n) { num = n; next = NULL; };
};
class List
{
protected:
Node *first, *last;
public:
Node *current;
public:
List() { first = last = current = NULL; };
void add_element (int n);
void delete_element();
void print(); // Izdrukā sarakstu
bool is_empty() { return (first == NULL); };
void start() { current = first; };
bool end() { return (current == NULL); };
void next(){if (!end())current = current -> next;};
Node* find(int i);
Node* addAfter(int i, List * l2);
~List();
};
int main()
{
List l, l2;
int k, i;
cout << "Type number: (0,to stop):\n";
cin >> k;
while (k!=0)
{
l.add_element (k);
cout << "Type number: (0, to stop):\n";
cin >> k;
};
cout << endl;
cout << "Type 2nd list numbers: (0,to stop):\n";
cin >> k;
while (k!=0)
{
l2.add_element (k);
cout << "Type 2nd list numbers: (0,to stop):\n";
cin >> k;
};
cout << endl;
l.print();
l2.print();
cout << "After which element do you want to insert second list?" << endl;
cin >> i;
l.addAfter(i, l2); // GETTING ERROR HERE.
l.print();
return 0;
}
你的例子看起来像前2,而不是后立即弹出一个堆栈到其它的最简单? –
@ Maartin1996在C/C++中,poistions通常从0开始。 –
'我该如何给这个函数l2的值作为参数?'好吧,您只需传递'List * l2'而不是'int num'。然后你改变第i个节点的指针到初始化'l2',并将'l2'的末尾改为(i + 1)个节点。这是作业吗?看起来你有非常基本的问题。 – freakish