【问题标题】:C++ Methods to insert element at beginning of a linked list and at specified index在链表的开头和指定索引处插入元素的 C++ 方法
【发布时间】:2014-03-17 00:43:38
【问题描述】:
对于列表类,我正在尝试创建一种方法来将节点添加到列表开头的链接列表,例如void List::prepend(const Item& it),以及在列表中的特定索引处插入元素的方法:void List::insert(const Item& it, int index)
所以我可以在开始使用这些方法时使用一些帮助。
我已经创建了一个添加到列表末尾的方法:
void List::append(const Item& it) {
Node *nodePtr = new Node(it, NULL);
if(mySize == 0)
{
myFirst = nodePtr;
}
else
{
myLast->myNext = nodePtr;
}
myLast = nodePtr;
mySize++;
}
但是另外两个不太好。
如果你想知道,我这里有一个 typedef:
typedef double Item;
【问题讨论】:
标签:
c++
insert
linked-list
nodes
prepend
【解决方案1】:
void List::prepend(const Item& it) {
Node *nodePtr = new Node(it, NULL);
if(mySize == 0)
{
//..
}
else
{
//..
}
++mySize;
}
void List::insert(const Item& it, int index) {
Node *nodePtr = new Node(it, NULL);
if(index == 0)
{
//..
}
Node *currentNode = myFirst;
int currentIndex = 0;
while(currentIndex < index - 1) {
//..
}
// insert before
// ..
++mySize;
}
自己填写 //.. 区域。
【解决方案2】:
这似乎是你的函数 (List::append(const Item& it)) 有点错误,你还没有将最后一个指针更新为 NULL。
【解决方案3】:
问题是您只保存最后一项。
您必须将第一项保存到 myFirst。
Answer these questions:
1. What happen if mySize = 1 ?
2. Where does nodePtr point next? ( nodePtr->next)
关于你的问题:
void List::prepend(const Item& it) {
Node *nodePtr = new Node(it, NULL);
if(mySize == 0)
{
myFirst = nodePtr;
}
else{
nodePtr->next = myFirst;
myFirst = nodePtr;
}
mySize++;
}