双链表无法正确打印值

时间:2019-10-06 22:06:22

标签: c++ pointers data-structures doubly-linked-list

当我调用方法以打印存储在我的双向链接列表的节点中的数据时,除了空字符串和0之外,什么都不会打印

#include <iostream>
#include <string>
using namespace std;

struct node {
    int weight;
    string name;
    node *nextname, *nextweight;
};
node *namehead = NULL, *weighthead = NULL;

bool isEmpty()
{
    if (namehead == NULL && weighthead == NULL)
        return true;
    else
        return false;
}

void addperson(int w, string n)
{
    node* newNode = new node;
    node *prev, *curr = newNode;
    if (isEmpty()) {
        namehead = newNode;
        weighthead = newNode;
    }
    else {
        curr = prev = namehead;
        if (curr->name > n) {
            namehead = newNode;
            newNode->nextname = curr;
        }
        else {
            do {
                if (curr->name <= n) {
                    prev = curr;
                    curr = curr->nextname;
                }
                else
                    break;
            } while (curr != NULL);
            prev->nextname = newNode;
            newNode->nextname = curr;
        }
        curr = prev = weighthead;
        if (curr->weight > w) {
            weighthead = newNode;
            newNode->nextweight = curr;
        }
        else {
            do {
                if (curr->weight <= w) {
                    prev = curr;
                    curr = curr->nextweight;
                }
                else
                    break;
            } while (curr != NULL);
            prev->nextweight = newNode;
            newNode->nextweight = curr;
        }
    }
}

void printname()
{
    node* curr = namehead;
    do {
        cout << curr->name << " - " << curr->weight << endl;
        curr = curr->nextname;
    } while (curr != NULL);
    cout << endl;
}

void printweight()
{
    node* curr = weighthead;
    do {
        cout << curr->name << " - " << curr->weight << endl;
        curr = curr->nextweight;
    } while (curr != NULL);
    cout << endl;
}

int main()
{
    int w = 0;
    string n;
    for (int i = 0; i < 15; i++) {
        cout << "Enter weight: ";
        cin >> w;
        if (w == -1)
            break;
        cout << "Enter name: ";
        cin >> n;
        addperson(w, n);
    }
    printname();
    printweight();
    return 0;
}

预期的输出(按名称):

John-220

史蒂文-190

泰勒-150

预期产量(以重量计):

泰勒-150

史蒂文-190

John-220

当前输出(双向):

“”-0

“”-0

“”-0

编辑 通过在注释中采纳有关在add方法中为临时节点实际分配值w(权重)和n(名称)的建议,此问题已得到解决。谢谢您的帮助。

curr->weight=w;
curr->name=n;

1 个答案:

答案 0 :(得分:1)

在add方法中将传递的值分配给权重,将名称成员分配给占位符节点:

curr->weight=w;
curr->name=n;