我第一次使用指針。我有一個程序,它將數字插入鏈表中,打印列表並從列表中刪除特定數字。除了當我嘗試刪除最後插入的號碼時,它工作。如何刪除添加到C++鏈接列表中的最後一個元素
Node.h
#ifndef Node_h
#define Node_h
#include <iostream>
using namespace std;
class Node
{
public:
int data;
Node *next;
public:
Node();
};
#endif
Node.cpp
#include "Node.h"
Node::Node()
{
}
LinkedList.h
#ifndef LinkedList_h
#define LinkedList_h
#include "Node.h"
class LinkedList
{
private:
Node *pL;
public:
LinkedList();
void insert(int nr1);
void deleteNr(int nr1);
void printL();
};
#endif
LinkedList.cpp //該程序創建一個 「鏈接列表」的數字
#include "LinkedList.h"
LinkedList::LinkedList()
{
pL = NULL;
}
void LinkedList::insert(int nr1)
{
Node *p = new Node;
p->data = nr1;
p->next = pL;
pL = p;
}
void LinkedList::deleteNr(int nr1)
{
Node *p = pL;
Node *p2 = pL;
while (p != NULL & p->data != nr1)
{
p2 = p;
p = p->next;
}
if (p != NULL)
{
p2->next = p->next;
delete p;
}
}
void LinkedList::printL()
{
Node *p = pL;
while (p != NULL)
{
cout << p->data << "-> ";
p = p->next;
}
}
的main.cpp
#include "LinkedList.h"
int menu();
//////// main /////////
int main()
{
int choice1, nr1;
LinkedList lk1;
choice1 = menu();
while (choice1 <= 3)
{
if (choice1 == 1)
{
cout << "Enter number." << endl;
cin >> nr1;
lk1.insert(nr1);
}
else if (choice1 == 2)
{
cout << "Enter number." << endl;
cin >> nr1;
lk1.deleteNr(nr1);
}
else if (choice1 == 3)
{
lk1.printL();
cout << endl << endl;
}
else if (choice1 == 4)
{
cout << "Exit the program." << endl;
system("pause");
exit(1);
}
choice1 = menu();
} // end while loop
}
int menu()
{
int choice1;
cout << "1. Insert a number into the linked-list." << endl;
cout << "2. Delete a number from the linked-list." << endl;
cout << "3. Print the linked-list." << endl;
cout << "4. Exit the program." << endl;
cout << "Enter choice." << endl;
cin >> choice1;
return choice1;
}
家庭作業?當您嘗試刪除最後插入的項目時會發生什麼? – Alex 2014-10-28 18:01:26
是的,這是一項家庭作業。當我嘗試刪除最後插入的項目時,它會崩潰。 – user3254558 2014-10-28 18:21:05
請注意,在你的刪除函數中,你需要一個'&',它需要'&&'。他們做不同的事情。 – Daniel 2014-10-28 18:25:41