2012-11-22 23 views
2

我只是測試一個結構是名稱,但它不會達到他們的函數。 這是完整的代碼至今:鏈表錯誤

更新:

#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 ); return 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’ 

回答

1

幾點:

  • 忘記malloc因爲你是用C工作++和使用newdelete
  • 你不需要指定該節點是一個結構再次每當你使用它時如此sizeof(Node)就夠了,但是你不會直接用malloc
  • 你的fu Node insertInOrder(Node p, string theName)接受一個具體的節點,並返回一個具體的Node但你的結構中的下一個字段是一個指向Node,我想你應該保持一致,你使用的是什麼,因爲你正在使用指針鏈接列表更合適
  • 你不能直接使用的比較操作符的值,一個字串(p == " ")之間,你應該檢查name場僅
+0

我更新了我的代碼。你介意看看嗎?對於(p =「」),我想檢查它是否爲空。 – TheChessDevil