链接列表初始化,删除和显示

时间:2015-03-04 17:32:49

标签: c++ hyperlink linked-list

我想要一个从1到10初始化链接列表的代码,然后删除最后一个节点并每次显示链接列表。 我写了这段代码,但第一个(WHILE)似乎是无限制的,它将是RAM的限制区域!

#include <iostream>
#include <conio.h>
using namespace std;

// function prototypes
void add_one_to_ten();
void delete_and_show();


struct node
{
    int dat;
    node* nxt;
};

node* Head = NULL;

int main()
{
    add_one_to_ten();
    delete_and_show();
    _getch();
    return 0;
}


//add_one_to_ten function body
void add_one_to_ten()
{
    for (int i = 1; i <= 10; i++)
    {
        node* temp = new node;
        temp->dat = i;
        temp->nxt = Head;
        Head = temp;
    }
}

//delete_and_show function body
void delete_and_show()
{
    node *temp1 = NULL, *temp2 = NULL, *temp3 = NULL;
    // this goes untill we reach a null LL
    while  (Head != NULL)
    {
        //this will show the LL each time
        temp3 = Head;
        while (temp3 != NULL)
        {
            cout << temp3->dat << "  ";
            temp3 = temp3->nxt;
        }
        cout << endl;
        if (Head == NULL)
            cout << "The list is empty.\n";
        else
        {
            temp1 = Head;
            while (temp1->nxt != NULL)
            {
                temp2 = temp1;
                temp1 = temp1->nxt;
            }
            delete temp1;
            temp2->nxt = NULL;

        }
    }
}

0 个答案:

没有答案