C ++ связанный список, стек (вроде) - PullRequest
2 голосов
/ 18 апреля 2011
#include <iostream>
using namespace std;

struct Node
{
    int item;   // storage for the node's item
    Node* next;   // pointer to the next node
};
/**************
use reference 
**************/
void addNode(Node*& head, int data , int& count) 
{
    Node * q;     // new node
    q = new Node;  // allocate memory for the new mode
    q->item = data;  // inserting data for the new node
    q->next = head;   // point to previous node ?? how would i do that? ( am i doing it correctly?)
    count++; // keep track of number of node
    head = q;
}

int main()
{
    int a, count = 0;
    int data;
    char callen;
    Node *head = NULL;

    do
    {
        cout << "please enter the data for the next node" << endl;
        cin >> data;
        addNode(head, data, count);
        cout << "do you wish to enter another node? (enter true or false)" << endl;
        cin >> callen;
    }while( callen != 'n' );

    // assuming this is the print function
    while(head != NULL)
    {
        cout << "output" << head->item << endl;
        head = head->next;                      //next element
    }

    system("pause");
    return 0;
}

Я попытался добавить новый элемент в список, как бы я переместил голову, как память LIFO (стек), чтобы последний элемент был в самом верху ..

Любая помощь будет оценена! В последнее время указатели и узлы портятся в моем мозгу ...

Ответы [ 6 ]

0 голосов
/ 07 июня 2011

То, как вы это делаете, реализуя функцию addNode как операцию push, уже перемещает головку, поэтому головка всегда будет указывать на последний добавленный вами элемент.

Поэтому, чтобы реализовать функцию удаления последнего добавленного элемента, вам просто нужно написать простую всплывающую операцию: скопировать адрес заголовка, сделать второй элемент новым заголовком и освободить память по скопированному адресу:

Node* oldHead = head;
head = head->next;
delete oldHead;
return head;
0 голосов
/ 18 апреля 2011

Похоже, вы пытаетесь немного узнать о списках ссылок.Круто!

В любом случае, я не собираюсь давать вам точный ответ, но я дам вам несколько указателей в псевдокоде, в частности, для вашей функции-члена addNode:

Node* addNode(Node* head, int data, int& count)
{
    create a new node
    let it point to head
    return the pointer to the new node for it to become the new head node
}

int main()
{
    // code...
    head = addNode(head, data, count);
    // more code...
}

Как визуально:

head
 \/
node A->node B->node C

new node->?
new node
     \/
    node A->node B->node C
0 голосов
/ 18 апреля 2011

Вы можете попробовать следующий модифицированный код.

#include <iostream>
using namespace std;

struct Node
{
    int item;   // storage for the node's item
    Node* next;   // pointer to the next node
};
/**************
use reference 
**************/
void addNode(Node*& head, int data , int& count) 
{
    Node * q;     // new node
    q = new Node;  // allocate memory for the new mode
    q->item = data;  // inserting data for the new node
    q->next = head;   // point to previous node ?? how would i do that? ( am i doing it correctly?)
    count++; // keep track of number of node
    head = q;
}

int main()
{
    int a, count = 0;
    int data;
    bool repeat;
    Node *head = NULL;
    // assuming it is an empty list at the beginning  and crating a new node below
    Node *temp;
    temp = new Node ;
    cout << "enter some data" << endl;
    cin >> a ;
    temp->item = a;
    temp->next = head;
    head = temp;
    //^^ assuming thats creating the first node ^^
    do
    {
        cout << "please enter the data for the next node" << endl;
        cin >> data;
        addNode(head, data, count);
        cout << "do you wish to enter another node? (enter true or false)" << endl;
        cin >> repeat;
    }
    while (repeat == true);


    // assuming this is the print function
    temp = head;
    while(temp != NULL)
    {
        cout << "output" << temp->item << endl;
        temp = temp->next;                      //next element
    }


    return 0;
}
0 голосов
/ 18 апреля 2011

В цикле do-while попробуйте это

addNode(data, count, head);

вместо

addNode( data, count );

Также измените подпись addNode следующим образом:

void addNode( int data , int& count , Node*& head)
0 голосов
/ 18 апреля 2011

Вы можете использовать std :: stack для LIFO.

int main()
{
    int a, count=0;
    int data;
    bool repeat;
    stl::stack<int> lifo;

    // assuming it is an empty list at the beginning  and crating a new node below
    cout << "enter some data" << endl;
    cin >> a ;
    lifo.push(a);
    do
    {
        cout << "please enter the data for the next node" <<endl;
        cin >> data;
        lifo.push(data);
        cout << "do you wish to enter another node? (enter true or false)" << endl;
        cin >> repeat;
    }
    while (repeat == true);


    // assuming this is the print function
    while(!lifo.empty()) {
        cout << lifo.pop() << endl;
    }

    system("pause");
    return 0;
}
0 голосов
/ 18 апреля 2011

Код не должен компилироваться, потому что вы используете переменную head в addNode, но head локально для main.

...