Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.67/3: Рейтинг темы: голосов - 3, средняя оценка - 4.67
0 / 0 / 0
Регистрация: 10.11.2013
Сообщений: 47

Нужно исправить ошибку

05.06.2014, 11:47. Показов 626. Ответов 1
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
/* source: http://runnable.com/Us53wIV1TEVWAAHd/how-to-search-a-node-in-a-linked-list-for-c%2B%2B
 * A sample code of search a node with a given value in a linked list,
 * and return the pointer of that node if it exists.
 * OUTLINE: traverse the linked list and compare the given value with 
 * each node, and return the pointer of the node  when they turn out
 * to be the same in value.
 */
 
#include <iostream>
#include <cstddef>
 
using std::cout;
using std::endl;
 
/*
 A linked list is a list constructed using pointers. It is not fixed in
 size and could grow and shrink while the program is running.
 
 A typical defination of list nodes contains at least two parts, both the
 content or date of each element and the pointer to the next element,
 which is shown in the figure below.
 
 +---------+
 |  Data   | -----> holds the data of this element in the list.
 +---------+
 | pointer | -----> is a pointer to the next element in the list.
 +---------+
 
 ***Attention***:
 The pointer holds the address of the next element, not the address of the
 data in the next element, even though they are the same in value sometimes.
 And It should be set to NULL while acting as the last node of the list.
 
 
 Implementation of the single linked list:
 +---------+    --->+---------+    --->+---------+
 |  Data   |    |   |  Data   |    |   |  Data   |
 +---------+    |   +---------+    |   +---------+
 | pointer |-----   | pointer |-----   | pointer |
 +---------+        +---------+        +---------+
 */
 
 
/* definition of the list node class */
class Node
{
    friend class LinkedList;
private:
    int _value; /* data, can be any data type, but use integer for easiness */
    Node *_pNext; /* pointer to the next node */
    
public:
    /* Constructors with No Arguments */
    Node(void)
    : _pNext(NULL)
    { }
    
    /* Constructors with a given value */
    Node(int val)
    : _value(val), _pNext(NULL)
    { }
    
    /* Constructors with a given value and a link of the next node */
    Node(int val, Node* next)
    : _value(val), _pNext(next)
    {}
    
    /* Getters */
    int getValue(void)
    { return _value; }
    
    Node* getNext(void)
    { return _pNext; }
};
 
/* definition of the linked list class */
class LinkedList
{
private:
    /* pointer of head node */
    Node *_pHead;
    /* pointer of tail node */
    Node *_pTail;
    
public:
    /* Constructors with a given value of a list node */
    LinkedList(int val);
    /* Destructor */
    ~LinkedList(void);
    
    /* Function to append a node to the end of a linked list */
    void tailAppend(int val);
    
    /* Function to search a node with a given value,
     and if succeeded return the node */
    Node* search(int val);
};
 
LinkedList::LinkedList(int val)
{
    /* Create a new node, acting as both the head and tail node */
    _pHead = new Node(val);
    _pTail = _pHead;
}
 
LinkedList::~LinkedList()
{
    /*
     * Leave it empty temporarily.
     * It will be described in detail in the example "How to delete a linkedlist".
     */
}
 
void LinkedList::tailAppend(int val)
{
    /* The list is empty? */
    if (_pHead == NULL) {
        /* the same to create a new list with a given value */
        _pTail = _pHead = new Node(val);
    }
    else
    {
        /* Append the new node to the tail */
        _pTail->_pNext = new Node(val);
        /* Update the tail pointer */
        _pTail = _pTail->_pNext;
    }
}
 
Node* LinkedList::search(int val)
{
    Node* pNode = _pHead;
    
    /* traverse the list */
    while (pNode != NULL) {
        /* Target! */
        if(pNode->_value == val)
        {
            return pNode;
        }
        /* move to the next one */
        pNode = pNode->_pNext;
    }
    return NULL;
}
 
int main(int argc, const char * argv[])
{
    /* Create a list with only one node */
    LinkedList list(1);
    /* Append 3 nodes to the end of the list */
    list.tailAppend(2);
    list.tailAppend(3);
    list.tailAppend(4);
    
    cout << "This list includes 4 nodes with values: 1 2 3 4" << endl;
    cout << endl;
    
    Node* node;
    /* Search the node with value 3 */
    cout << "Searching a node with value 3" << endl;
    node = list.search(3);
    /* output the result */
    if (node != NULL)
        cout << "Result: Find the node with value " << node->getValue() << endl;
    
    else
        cout << "Result: Cannot find the node with value 3" << endl;
    cout << endl;
    
    /* Search the node with value 5 */
    cout << "Searching a node with value 5" << endl;
    node = list.search(5);
    /* output the result */
    if (node != NULL)
        cout << "Result: Find the node with value " << node->getValue() << endl;
    
    else
        cout << "Result: Cannot find the node with value 5" << endl;
    
    return 0;
}
Добавлено через 29 секунд
можете помочь пожалуйста
0
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
05.06.2014, 11:47
Ответы с готовыми решениями:

Нужно исправить ошибку
При выполнении задачи необходимо создать массив структуры(Person: Фамилия, Имя, Отчество, Адрес, Пол, Образование, Год рождения) , ввести...

Нужно исправить ошибку
Помогите исправить ошибку. Спасибо #include &lt;iostream&gt; #include &lt;stdlib.h&gt; #include &lt;Windows.h&gt; #include &lt;math.h&gt; using...

Нужно исправить ошибку
При переводе из 10 в 2 систему счисления выдает иногда неправильный ответ. Как это можно исправить? #include &lt;iostream&gt; #include...

1
Модератор
Эксперт С++
 Аватар для zss
13771 / 10964 / 6491
Регистрация: 18.12.2011
Сообщений: 29,241
05.06.2014, 15:10
А она действительно есть?
Вроде все работает адекватно.
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
05.06.2014, 15:10
Помогаю со студенческими работами здесь

Нужно исправить ошибку
Ошибки Error 1 error LNK2001: unresolved external symbol &quot;public: __thiscall Exceptions::OutOfBound::OutOfBound(int)&quot;...

Нужно исправить ошибку
Здравствуйте уважаемые форумчане. Не молчите пожалуйста, ответьте хоть кто-нибудь. Сколько писал никто не отвечает. Может потому что...

Нужно исправить ошибку
Здравствуйте. Visual Studio ругается на 20-ю строку. Подчеркивает массив &quot;Koord&quot; и выдает такую ошибку: &quot;double* Koord выражение...

Инверсия нужно исправить ошибку
#include &lt;iostream&gt; #include&lt;iomanip&gt; #include&lt;cmath&gt; using namespace std; int main() { setlocale( LC_ALL,&quot;Russian&quot; ); ...

Нужно исправить ошибку в коде!
Вот задание: Создать приложение для вычисления значения арифметического выражения, которое может включать в себя действительные числа, а...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
2
Ответ Создать тему
Новые блоги и статьи
Установка Android SDK, NDK, JDK, CMake и т.д.
8Observer8 25.01.2026
Содержание блога Перейдите по ссылке: https:/ / developer. android. com/ studio и в самом низу страницы кликните по архиву "commandlinetools-win-xxxxxx_latest. zip" Извлеките архив и вы увидите. . .
Вывод текста со шрифтом TTF на Android с помощью библиотеки SDL3_ttf
8Observer8 25.01.2026
Содержание блога Если у вас не установлены Android SDK, NDK, JDK, и т. д. то сделайте это по следующей инструкции: Установка Android SDK, NDK, JDK, CMake и т. д. Сборка примера Скачайте. . .
Использование SDL3-callbacks вместо функции main() на Android, Desktop и WebAssembly
8Observer8 24.01.2026
Содержание блога Если вы откроете примеры для начинающих на официальном репозитории SDL3 в папке: examples, то вы увидите, что все примеры используют следующие четыре обязательные функции, а. . .
моя боль
iceja 24.01.2026
Выложила интерполяцию кубическими сплайнами www. iceja. net REST сервисы временно не работают, только через Web. Написала за 56 рабочих часов этот сайт с нуля. При помощи perplexity. ai PRO , при. . .
Модель сукцессии микоризы
anaschu 24.01.2026
Решили писать научную статью с неким РОманом
http://iceja.net/ математические сервисы
iceja 20.01.2026
Обновила свой сайт http:/ / iceja. net/ , приделала Fast Fourier Transform экстраполяцию сигналов. Однако предсказывает далеко не каждый сигнал (см ограничения http:/ / iceja. net/ fourier/ docs ). Также. . .
http://iceja.net/ сервер решения полиномов
iceja 18.01.2026
Выкатила http:/ / iceja. net/ сервер решения полиномов (находит действительные корни полиномов методом Штурма). На сайте документация по API, но скажу прямо VPS слабенький и 200 000 полиномов. . .
Расчёт переходных процессов в цепи постоянного тока
igorrr37 16.01.2026
/ * Дана цепь(не выше 3-го порядка) постоянного тока с элементами R, L, C, k(ключ), U, E, J. Программа находит переходные токи и напряжения на элементах схемы классическим методом(1 и 2 з-ны. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru