我是第一次使用指针。我有一个程序,可以在链接列表中插入数字,打印列表,然后从列表中删除特定的数字。除我尝试删除最后插入的号码外,它均有效。
节点
#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;
}
您需要添加代码来处理给定输入对应于列表中第一项的情况。
void LinkedList::deleteNr(int nr1)
{
Node *p = pL;
if ( p != NULL && p->data == nr1 )
{
pL = p->next;
delete p;
return;
}
Node *p2 = pL;
while (p != NULL && p->data != nr1)
{
p2 = p;
p = p->next;
}
if (p != NULL)
{
p2->next = p->next;
delete p;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句