h*****g 发帖数: 944 | 1 执行的时候总说segmentation fault,
谢谢大家指点
===================================
#include
using namespace std;
template< class T>
class ListNode{
public:
T data;
ListNode(T v);
ListNode< T > *next;
};
template ListNode < T >::ListNode(T v)
{
}
template
class LinkedList{
ListNode *head;
public:
LinkedList(){}
~LinkedList(){
while(head){
ListNode* next = head->next;
delete head;
head = next;
}
}
void Add (T v){
ListNode *n = new ListNode(v);
head->next= n;
}
void Delete(T v){
ListNode *current= head;
//ListNode *next_node;
while (current!=NULL){
if((current->next)->data == v){
// next_node = current->next
current = current->next->next;
}
else
current = current->next;
}
}
};
int main(){
LinkedList hehe;
// hehe.Add(10);
// hehe.Add(20);
} |
j***i 发帖数: 1278 | 2 add 后 n-》next没有set吧
【在 h*****g 的大作中提到】 : 执行的时候总说segmentation fault, : 谢谢大家指点 : =================================== : #include : using namespace std; : template< class T> : class ListNode{ : public: : T data; : ListNode(T v);
|
g*********s 发帖数: 1782 | 3 no, it's not because of that.
in add(), head is not initialized while head->next is referred.
1. head should be initialized as NULL in ctor.
2. add() is doing push_back(). a tail pointer is needed.
add(int v)
{
Node* tmp = new Node(v);
if (head == NULL) {
head = tail = tmp;
}
else {
tail->next = tmp;
tail = tail->next;
}
}
【在 j***i 的大作中提到】 : add 后 n-》next没有set吧
|
g*********s 发帖数: 1782 | 4 if add() is supposed to do push_front(), do the following:
add(int v)
{
Node* tmp = new Node(v);
tmp->next = head;
head = tmp;
}
head still needs to be initialized as NULL in ctor.
【在 g*********s 的大作中提到】 : no, it's not because of that. : in add(), head is not initialized while head->next is referred. : 1. head should be initialized as NULL in ctor. : 2. add() is doing push_back(). a tail pointer is needed. : add(int v) : { : Node* tmp = new Node(v); : if (head == NULL) { : head = tail = tmp; : }
|
d*****o 发帖数: 28 | 5
The head did not initialized in LinkedList class.
the head is null, if you add a node to it like head->next = ...
it will have segment fault error
【在 h*****g 的大作中提到】 : 执行的时候总说segmentation fault, : 谢谢大家指点 : =================================== : #include : using namespace std; : template< class T> : class ListNode{ : public: : T data; : ListNode(T v);
|
f****4 发帖数: 1359 | 6 TA也不帮调代码的吧?
Google一下gdb怎么用,你可以自己找原因 |