如何为链表插入元素

时间:2013-03-13 20:42:03

标签: c++ algorithm linked-list

//我不知道如何插入元素,并输出整个列表。

#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;
}

1 个答案:

答案 0 :(得分:0)

仔细阅读:

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

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