2017-08-27 11 views
0

頭文件:這是傳遞int num時創建搜索函數的正確方法嗎?使用鏈表libary

#ifndef LL_H 
#define LL_H 

// include this library to use NULL, otherwise use nullptr instead 
#include <cstddef> 

// include iostream so anything that includes this file can use cout 
#include <iostream> 

// Struct which will be the building block of our list 
struct node 
{ 
    int val; 
    node* next; 
}; 

// Contents of 11.h 
// Linked list class definition 
class LL 
{ 
public: 
    LL(); 
    bool removeFront(); 
    bool removeBack(); 
    node* search(int); 
    void print(); 
private: 
    node* head; 
}; 
#endif 

源文件:

#include "ll.h" 

LL::LL() 
{ 
    head = NULL; 
} 
void LL::search (int num)//heading of the function 
{ 
    node* newNode = new node; 
     newNode->val = num; 
     newNode->next = NULL; 

    while (newNode == NULL) 
    { 
     if (newNode->val == num) 
     { 
      return newNode; 
     } 
     newNode = newNode->next; //point to the next node 
    } 
    return; //not sure if needed 
} 

程序將在名爲「cmd.txt」一個 文本文件,將指示讀什麼操作運行。我們的程序應該實現一個C++類,它將用來表示鏈表。

+0

所以要使用由你來實現圖書館或鏈接列表中提供的鏈接列表? – Fureeish

+0

'while(curNode == NULL)':這應該做什麼? – AndyG

+0

你的代碼有問題嗎? 'void LL:search'看起來錯誤,考慮到它被聲明爲'node * search',並且有一個冒號是錯誤的。 – Tas

回答

1

搜索應該更像:

node* LL::Search(int num) 
{ 
    node* current = head; 
    while (current != null) 
    { 
     if (current->val == num) 
     { 
      return current; 
     } 
     current = current->next; 
    } 
    return null; 
} 
+0

抱怨num有一個編譯器錯誤。 –

0

這是正確的格式

node* LL::search(int num) 
    { 
     node* newNode = new node; 
     newNode = head; 
     while (newNode->next != NULL) 
     { 
      if (newNode->val == num) 
      { 
       return newNode; 
      } 
     newNode = newNode->next; 
     } 
     return NULL; 
    } 
相關問題