1️⃣3️⃣ 循环链表
❓ 不知道为什么循环链表不能用析构函数,写了就出错。
#include <iostream>
using namespace std;
class List{
private:
struct Node{
int data;
Node* next;
Node(){}
Node(int d){
data = d;
next = 0;
}
};
Node* head;
public:
List();
void Insert(const int i);
void Delete (const int i);
void Show()const;
};
List::List(){
head = new Node;
head->next = head;
}
void List::Insert(const int i){
Node* p = new Node(i);
p->next = head->next;
head->next = p;
}
void List::Delete(const int i){
Node* p = head->next;
Node* q=head;
while(p!=head&&p->data != i){
q = p;
p = p->next;
}
if(p!=head){
q->next = p->next;
delete p;
}
}
void List::Show()const{
Node* p = head->next;
while(p!=head){
cout << p->data << " " ;
p = p->next;
}
}
int main() {
List l1;
l1.Insert(1);
l1.Insert(2);
l1.Insert(3);
l1.Insert(4);
l1.Show(); cout << endl;
l1.Delete(2);
l1.Show(); cout << endl;
return 0;
}