2

我只是在其中一个名为 name 的结构上测试该函数,但它不会到达它们。这是到目前为止的完整代码:

更新:

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

struct Node{
    string name;
    string address;
    int phoneNum;
    struct Node* next;
};

Node insertInOrder(Node p, string theName);
void push(struct Node*& head, string theName);


int main(){

    cout<<"\tEnter S or s to show the list contents \n"
        <<"\tEnter A or a to add a node to the list \n"
        <<"\tEnter D or d to delete a node from the list \n"
        <<"\tEnter Q or q to quiet the program \n"
    <<"Make your selection: "<<endl;

    struct Node* newNode = new Node;
    push(newNode, "yeah");

    cout<<newNode;

    return 0;

}

void push(struct Node*& head, string theName){
    struct Node* newNode = new Node;
    newNode->name = theName;
    newNode->next = head;
    head = newNode;
}

Node insertInOrder(Node p, string theName){
    if(p == NULL || p.name >= theName){
        return new Node(p, theName);
    }
    else{
            p.next = insertInOrder(p.next, theName);
            return p;
        }
    }

我收到一条错误消息:此代码的“sizeof”对不完整类型“节点”的无效应用:

    void push(struct Node*& head, string theName){
    struct Node* newNode = malloc(sizeof(struct Node));
    newNode->name = theName;
    newNode->next = head;
    head = newNode;
}

我正在尝试将此代码转换为我的代码,但出现错误:

 Node insertInOrder( int k, Node p ) {
   if( p == " " || p.item >= k ) 
      return new Node( k, p ); 
   else {
      p.next = insertInOrder( k, p.next ); 
      return p;
   }
} 

我是这样翻译的:

Node insertInOrder(Node p, string theName){
    if(p == " " || p.name >= theName){
        return new Node(p, theName);
    }
    else{
            p.next = insertInOrder(p.next, theName);
            return p;
        }
    }

这是此代码的错误:

 if(p == " " || p.name >= theName){
        return new Node(p, theName);

错误:

- comparison with string literal results in unspecified behaviour [-Waddress]
- request for member ‘name’ in ‘p’, which is of pointer type ‘Node*’ (maybe you meant to use ‘-
 >’ ?)
- comparison between distinct pointer types ‘Node*’ and ‘const char*’ lacks a cast [-
 fpermissive]

p.next = insertInOrder(p.next, theName); 返回 p;

错误:

Invalid arguments ' Candidates are: Node insertInOrder(Node, std::basic_string<char,std::char_traits<char>,std::allocator<char>>) '
- could not convert ‘p.Node::next’ from ‘Node*’ to ‘Node’
4

1 回答 1

1

几点:

  • 忘记malloc,因为您正在使用 C++ 并使用newanddelete
  • 每当您使用它时,您都不需要再次指定该节点是一个结构,这样sizeof(Node)就足够了,但您不会直接使用 malloc
  • 你的函数Node insertInOrder(Node p, string theName)接受一个具体的 Node 并返回一个具体Node的但你结构中的 next 字段是一个指向 a 的指针Node,我想你应该在你使用的内容上保持一致,因为你正在使用指针处理链表更合适
  • 您不能直接在值和字符串文字 ( ) 之间使用比较运算符p == " ",您应该只检查name字段
于 2012-11-22T15:19:13.887 回答