Redian新闻
>
【我自己写的LinkedList为什么总有错?】
avatar
【我自己写的LinkedList为什么总有错?】# JobHunting - 待字闺中
h*g
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);
}
avatar
j*i
2
add 后 n-》next没有set吧

【在 h*****g 的大作中提到】
: 执行的时候总说segmentation fault,
: 谢谢大家指点
: ===================================
: #include
: using namespace std;
: template< class T>
: class ListNode{
: public:
: T data;
: ListNode(T v);

avatar
g*s
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吧
avatar
g*s
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;
: }

avatar
d*o
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);

avatar
f*4
6
TA也不帮调代码的吧?
Google一下gdb怎么用,你可以自己找原因
相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。