gpt4 book ai didi

c++ - 2-way intlist c++ push_front

转载 作者:行者123 更新时间:2023-11-28 06:08:29 26 4
gpt4 key购买 nike

我正在编写一个 2-way Intlist,其中每个节点都有对其上一个和下一个节点的引用。一切似乎都很好,但是当我使用 Push_front() 方法在开头添加节点时,它们没有上一个引用。

list.push_front(2);
list.push_front(1);

2 不会引用 1。这是我的代码。

内部节点

#ifndef INTNODE_H_
#define INTNODE_H_

class IntNode {
friend class IntList;
private:
int data;
IntNode * prev;
IntNode * next;
public:
IntNode(IntNode * previous = 0, IntNode * nextnode = 0):data(0), prev(previous), next(nextnode){};
IntNode(int data = 0, IntNode * previous = 0, IntNode * nextnode = 0):data(data),prev(previous),next(nextnode){};
int getData() const {return data;}
IntNode * getprev() const {return prev;}
IntNode * getnext() const {return next;}
void setPrev(IntNode * node){this->prev = node;}
};
#endif

Intlist.h

#ifndef INTLIST_H_
#define INTLIST_H_

#include "IntNode.h"
#include <iostream>
class IntList {
private:
IntNode * first;
public:
IntList():first(0){};
IntList(IntNode * firstnode):first(firstnode){};
void push_back(int data);
void push_front(int data);
void delete_first();
void delete_last();
friend std::ostream& operator<<(std::ostream& out, const IntList& list);
IntNode* getFirst() const {return first;}
};
#endif

IntList.cpp

#include "IntList.h"

void IntList::push_back(int data){
if(first){
IntNode * node = first;
while(node->next != 0){
node = node->next;
}
node->next = new IntNode(data,node,0);
}else{
first = new IntNode(data);
}
}

void IntList::push_front(int data){
//first = new IntNode(data,0,first); //prev = 0, no reference when is sec node
first->setPrev(new IntNode(data,0,first));
}

void IntList::delete_first(){
if(first){
if(first->next != 0){
first = first->next;
first->setPrev(0);
}else{first = 0;}
}
}

void IntList::delete_last(){
if(first){
IntNode * temp = first;
while(temp->next != 0){temp = temp->next;}
IntNode * node = temp->prev;
node->next=0;
delete temp;
}
}
std::ostream& operator<<(std::ostream& out, const IntList& list){
if(list.first){
IntNode * node = list.first;
out << node->getData();
while(node->getnext() !=0){
node = node->getnext();
out << node->getData();
}
}
return out;
}

最佳答案

如果你想实现一个 Push_front 新添加的节点成为第一个节点,这不会发生在你的代码中。

这应该有效。

void IntList::push_front(int data)
{
IntNode *newfirst = new IntNode(data, 0, first);
if (first) {
first->setPrev(newFirst);
}
first = newFirst;
}

关于c++ - 2-way intlist c++ push_front,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31852899/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com