2路intlist c ++ push_front

时间:2015-08-06 10:07:58

标签: c++ list nodes

我正在编写一个双向Intlist,其中每个节点都有对其上一个节点和下一个节点的引用。一切似乎都没问题,但是当我使用Push_front()方法在开始时添加节点时,它们没有上一个参考。

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

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

IntNode

#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;
}

1 个答案:

答案 0 :(得分:1)

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

这应该有用。

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