【问题标题】:How to insert element for the linked list如何为链表插入元素
【发布时间】:2013-03-13 20:42:03
【问题描述】:

//我不知道怎么插入元素,输出整个列表。

#include <iostream>
using namespace std;
class IntElement 
{
public:
    class IntElement *next;
    int data;
bool insertInFront( IntElement** head, int data )
{
IntElement *newElem = new IntElement;
if( !newElem ) return false;
newElem->data = data;
*head = newElem;
return true;
}
bool insertElement(IntElement **head, int d)
{
    IntElement *newElem = new IntElement;
    newElem->data=d;
    newElem=*head;
    *head=newElem->next;
    return true;
}
void print(IntElement **head)
{
     if(*head!=NULL)
    {
        cout<<(*head)->data<<endl;
        *head=(*head)->next;
    }
}
} ;
int main()
{

    IntElement *T=new IntElement;
    T->insertInFront( &T,7);
    T->insertInFront(&T,9);
    T->insertInFront(&T,213);
    T->insertInFront(&T,33);
    T->insertElement(&T,123);
    T->print(&T);
    system("pause");
    return 0;
}

【问题讨论】:

  • 尝试使用std::list。见std::list::push_back()。这些已经为您测试过了。您不必浪费时间创建自己的链表。

标签: c++ algorithm linked-list


【解决方案1】:

仔细阅读:

IntElement *newElem = new IntElement;
newElem->data=d;
newElem=*head;
*head=newElem->next;
return true;

我怀疑newElem = *head; 正在做你想做的事。

【讨论】:

  • 想想事情的顺序——在你将*head 分配给newElement 之后,你有什么东西仍然指向你分配的新项目吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-02
  • 2013-02-17
  • 2021-09-05
  • 2014-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多