2014-12-23 2 views
0

Моя цель - создать функцию, которая ищет номер уже в списке и распечатать его.
Моя первоначальная идея состояла в том, чтобы следовать моей функции remove, которая просматривает список до тех пор, пока не найдет номер (затем удалить).
Это казалось логичным способом кодирования функции поиска. Если это неверно, как мне изменить его для поиска по моему списку и показать, что номер найден?
У меня есть узлы * head, * current и * temp, а также указатель узла следующий и номер как тип данных в классе по файлу .h.
Спасибо.
ПРИМЕЧАНИЕ - Я использовал функцию remove() под функцией search().Функция поиска в связанном списке - C++

#include <iostream>             
#include <string>             
#include <fstream>             
#include "LinkedList.h" 

using namespace SDI; 

int main() 
{ 
    LinkedList menu; 

    menu.insert(5);      
    menu.insert(4); 
    menu.insert(2); 
    menu.insert(3); 
    menu.insert(8); 
    menu.remove(4); 
    menu.reverse(); 
    menu.display(); 
    menu.search(2); 
    system("pause"); 

}; 


LinkedList::LinkedList()    
{ 
    head = NULL; 
    current = NULL; 
    temp = NULL; 
}; 


LinkedList::~LinkedList()   
{ 

}; 


void LinkedList::insert(int add)         //insert function, data is stored in add from function body 
{ 
    Node* newnode = new Node;          //definition of add node, make new node and make node* point to it 
    newnode->next = NULL;           //point and set up to last node in the list (nothing) 
    newnode->number = add;           //adds data to list 

    if (head != NULL)            //if head is pointing to object then we have list 
    { 
     current = head;            //make current pointer point to head 
     while (current->next != NULL)        //check to see if end at list, is it the last node? 
     { 
      current = current->next;        //advances current pointer to end of list 
     } 
     current->next = newnode;         //adds new node next to value already stored 
    } 
    else 
    { 
     head = newnode;            //if we don't have element in list 
    } 
}; 


void LinkedList::remove(int remove)         //remove function, data is stored in remove from function body 
{ 
    Node* remove1 = NULL;           //searches through for same value in remove and deletes 
    temp = head; 
    current = head; 
    while (current != NULL && current->number != remove)   //check if current node is one we want to delete...if not advance current pointer to next one 
    { 
     temp = current;            //keep temp pointer one step behind 
     current = current->next;         //advance to next node, traverse list till at the end 
    } 
    if (current == NULL)           //pass through whole list and value not found 
    { 
     std::cout << "N/A\n"; 
     delete remove1;            //removes spare number floating around in memory 
    } 
    else 
    { 
     remove1 = current;           //pointing to value we want to delete 
     current = current->next;         //advances current pointer to next node 
     temp->next = current;          //stops hole that occurs in list, patches this up 
     if (remove1 == head)          //if pointer is pointing to front of list 
     { 
      head = head->next;          //advance the head to next 
      temp = NULL; 
     } 

     delete remove1; 
    } 
}; 


void LinkedList::search(int searchNum) 
{ 
    Node* searchnumber = nullptr; 
    temp = head; 
    current = head; 

    while (current != NULL && current->number != searchNum) 
    { 
     temp = current; 
     current = current->next; 
    } 
    if (current != NULL) 
    { 
     searchnumber = current; 
     current = current->next; 
     std::cout << "-" << searchnumber << " Found"; 
    } 
    else 
    { 
     std::cout << "N/A"; 
    } 
}; 


void LinkedList::display() 
{ 
    current = head;             //point to start of list 

    while (current != NULL)           //while it points to something in list 
    { 
     std::cout << current->number;        //display list starting from start 
     current = current->next;         //advance to next pointer 
    } 
}; 


void LinkedList::reverse() 
{ 
    Node *new_head = nullptr;          //create new head as we want it to start from last element 

    for (current = head; current;)         //same as display, ask it to go through list from head then outside loop assign to new head and switch sides 
    { 
     temp = current;            //keep temp pointer one step behind 
     current = current->next;         //goes through each element in the list 
     temp->next = new_head;          //scrolls through backwards from new head 
     new_head = temp;            
    } 

    head = new_head;            //assign head to new head 
}; 
+4

В чем вопрос? –

+0

Если я правильно написал функцию поиска, чтобы сделать то, что я хочу сделать – Ryan

+0

Вы можете просто запустить список и найти элемент. В худшем случае это O (n) ... не очень эффективный. Вместо этого вы можете искать двоичное дерево поиска (поиск худшего случая O (ln (n))). – TravisJ

ответ

1

Ваш алгоритм поиска кажется неправильным. Измените его на:

if (current != NULL) // (current == NULL) is wrong because it means the value wasn't found 
{ 
    searchnumber = current; 
    current = current->next; 
    std::cout << "-" << searchnumber->number << " Found"; // here searchnumber is the node's address. You need to print its value, so use searchnumber->number 
} 

И вам не нужно удалять узлы, пока не найдете нужное значение.
Вы можете использовать свой алгоритм поиска, чтобы узнать, есть ли число в списке. Если это то что ты хочешь.

+0

Он работает, но он отображает случайное число вместо числа, которое я хотел найти. Например. 000nbn45found – Ryan

+0

'if (current == NULL)' как, черт возьми, он покажет номер? это нуль ... вы знаете, что я имею в виду ... измените его, и я думаю, что он покажет фактические цифры –

+0

И было бы здорово, если бы вы указали ввод, для которого ваш код не работает, а также ваш полный код –

0

Хотя список неупорядочен, сравнение алгоритмов поиска не имеет никакого смысла. Просто перебирайте все узлы один за другим и применяйте критерии соответствия.

Смежные вопросы