链接列表清除和插入函数在C ++中

时间:2014-03-27 01:00:50

标签: c++ linked-list

我几周来一直在与Pointers和坦率的C ++斗争。我有一个放弃的学校项目(截止日期已经过去)。尽管我无法将其转换为练习,但我仍然坚持使用我的清晰方法,但我可能还有其他方法可以做到这一点。

.h文件

using namespace std;

template < typename T >   // Forward declaration of the SimpList class
class SimpList;

//--------------------------------------------------------------------
//
// Definition of class Node<T>
//
//--------------------------------------------------------------------

template < typename T >
class Node                 // Node class for the SimpList class
{
  private:

    // Constructors

    Node () { next = 0; }  // default constructor

    // Complete the definition inline

    Node ( const T &initItem, Node<T> *ptr ) {
        value=initItem;
        next=ptr;
    }

    // Data members

    T           value;   // Node data item
    Node        *next;  // Pointer to the next node

  friend class SimpList<T>;
};

//--------------------------------------------------------------------
//
// Definition of class SimpList<T>
//
//--------------------------------------------------------------------

template < typename T >
class SimpList
{
  public:

    // Constructor (add your code inline)

    SimpList ()
    {
        head = &PHONY;
        length=0;
      // complete the data member intialization
    }

    // Destructor (add your code inline)

    ~SimpList () { clear();}

    // List manipulation operations

    void insert ( const T &newitem );   // insert a data item

    bool remove ( T &item );            // remove data item

    bool find ( T &item ) const;        // find data item

    void clear ();                      // empty the list

    // (add your code inline)
    bool isEmpty () const { 
        if (length == 0)
        {
            return true;
        }
        else
        {   
            return false;
        }
        }

    // length accessor method (add your code inline)
    int size () const { return length; }

    // print the list items
    void print () const;

  private: // data members

    Node<T> PHONY ;      // empty node that anchors the list

    Node<T> *head;      // pointer to the beginning of the list

    int length;         // length of list
};

//--------------------------------------------------------------------
//
// Implementation section
//
//--------------------------------------------------------------------

template < typename T >
void SimpList<T>::print() const
{
  if (length == 0)
  {
    cout << "List is empty." << endl;
    return;
  }

  Node<T> *ptr=head;
  while (ptr != NULL)
  {

    cout << ptr->value << "  ";
    ptr = ptr->next;
  }
  cout << endl;
}

template <typename T>
void SimpList<T>::insert ( const T &newitem )
{
Node<T> *p = new Node<T>;
p->value = newitem;
p->next = head;
head = p;
length++;

}

template <typename T>
void SimpList<T>::clear ()
{

    Node<T> *p = head->next;

    while(p != NULL)
{
    head=head->next;
    delete p;
}

length = 0;

}
template <typename T>
bool SimpList<T>::find ( T &item ) const
{
Node<T> *p;
    for(p=head; p!=NULL; p=p->next)
        if(p->value==item) break;

      if(p!=NULL)
      {
          item=p->value;
        return true;
      }
      else
      {
          return false;
      }


}
template <typename T>
bool SimpList<T>::remove ( T &item )
{
Node<T> *p,*c;

        for(c=head; c!=NULL;p=c,c=c->next)
            if(c->value==item) break;

        if(c!=NULL)
        {
            item=c->value;
            p->next=c->next;
            delete c;
            length --;
            for(c=head;c!=NULL;c=c->next)
            cout<<c->value<<" ";
            return true;
        }
        else
            return false;


}

.cpp文件在这里。

#include <iostream>
#include <string>
#include "simpList.h"


int main()
{
  SimpList<int> intList;   // (empty) list of integers

  cout << "Let's build a sorted list of integers." << endl;
  cout << endl << "Uninitialized List: ";
  intList.print();
  cout << endl << "Length: " << intList.size() << endl;

  int intData[] = { 5, 3, -2, 7, 9, -8, 1, -4 };

  for (int i=0; i<8; i++){
    intList.insert( intData[i] );
  }
  cout << endl << "After inserting 8 integers: ";
  intList.print();
  cout << endl << "Length: " << intList.size() << endl;

  cout << endl << "--- Testing the \"find\" method:" << endl;

  int t = 5;
  bool ret = intList.find(t);

  cout << endl << t << " is in the list: "
     << (ret ? "true" : "false") << endl;

   t = 6;
  ret = intList.find(t);

 cout << endl << t << " is in the list: "
       << (ret ? "true" : "false") << endl;

  cout << endl << "--- Testing the \"remove\" method:" << endl;

  t = 5;
  ret = intList.remove(t);

  cout << endl << t << " has been removed: "
       << (ret ? "true" : "false") << endl;

  cout << endl << "Remaining list: ";
  intList.print();
  cout << endl << "Length: " << intList.size() << endl;

  cout << endl << "--- Testing the \"clear\" method:" << endl << endl;

  intList.clear();
  intList.print();
  cout << endl << "Length: " << intList.size() << endl;

  cout << endl << "--- Testing the \"isEmpty\" predicate:" << endl;

  cout << endl << "The integer list is now empty: "
       << (intList.isEmpty()? "true" : "false") << endl << endl;

  cout << "Now, let's build a sorted list of strings." << endl;

  string strData[] = { "Maria", "Ann", "Emily", "Vivian",
                       "Beth", "Carla", "Susan" };

  SimpList<string> strList;

  for (int i=0; i<7; i++){
    strList.insert( strData[i] );
  }
  cout << endl << "After inserting 7 names:" << endl;
  strList.print();
  cout << endl << "Length: " << strList.size() << endl;

  cout << endl << "--- Testing the \"remove\" method:" << endl;
  cout << endl << "Bye Carla!" << endl;

  string str = "Carla";
 ret = strList.remove(str);

  cout << endl << str << " has been removed: "
      << (ret ? "true" : "false") << endl;

  cout << endl << "Remaining list:" << endl;
  strList.print();
  cout << endl << "Length: " << strList.size() << endl;

  cout << endl << "--- Testing the \"insert\" method:" << endl;
  cout << endl << "Bienvenue Pauline!" << endl;

  string nom = "Pauline";
  strList.insert(nom);

  cout << endl << "Extended list:" << endl;
  strList.print();
  cout << endl << "Length: " << strList.size() << endl;

  cout << endl << "--- Auf Wiedersehen!" << endl;`enter code here`
  cout << endl << "End of \"main()\"." << endl
       << "At this point, the destructor is called." << endl;


system("PAUSE");}
  1. 固定

  2. 当打印出列表中的项目时,它会打印所有项目以及-858993460,并且我已经用尽了解如何修复它。

  3. 我非常感谢你们的帮助或者指向正确的方向。

2 个答案:

答案 0 :(得分:0)

通过函数的逻辑思考。将其绘制成纸上的方框,并计算出需要移动和删除指针的顺序

考虑删除链表的这个序列。

while(there is still an item left in the list)  {
    take a copy of the existing head pointer
    move the head pointer to the next item
    delete the old head using the copy of the head pointer you took before changing it
}
set length to zero

请注意,在普通列表中,当列表为空时,头指针应设置为零,并且“下一个”指针在列表的最后一项上将为零。

答案 1 :(得分:0)

在明确的功能中尝试这个

while(head!=NULL)

。 {node * p = head; 。头=头戴式&gt;接着, 。删除p 。 }

并确保最初将head设置为null。否则在上次迭代过程中会占用一些垃圾值。