c_cpp 链表类模板代码
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 链表类模板代码相关的知识,希望对你有一定的参考价值。
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node *next;
Node(int da = 0, Node *p = NULL) {
this->data = da;
this->next = p;
}
};
class List {
private:
Node *head, *tail;
int position;
public:
List() { head = tail = NULL; };
~List() {
delete head;
delete tail;
}
void print();
void Insert(int da = 0);
void Delete(int da = 0);
void Search(int da = 0);
int getValueAt(int position);
void setValueAt(int position, int da);
};
int List::getValueAt(int position) {
Node *p = head;
if (p == NULL) {
cout << "The List is Empty" << endl;
}
else {
int posi = 0;
while (p != NULL && posi != position) {
posi++;
p = p->next;
}
if (p == NULL) {
cout << "There is no value of this position in this List" << endl;
}
else {
cout << "In this Position,the value is " << p->data << endl;
}
}
return p->data;
}
void List::setValueAt(int position, int da) {
Node *p = head;
if (p == NULL) {
cout << "The List is Empty!" << endl;
}
else {
int posi = 0;
while (p != NULL && posi != position) {
posi++;
p = p->next;
}
if (p == NULL) {
cout << "There is No Position in this List" << endl;
}
else {
p->data = da;
cout << "The Value in this position has been Updated!" << endl;
}
}
}
void List::Search(int da) {
Node *p = head;
if (p == NULL) {
cout << "The List is Empty" << endl;
return;
}
int count = 0;
while (p != NULL && p->data != da) {
p = p->next;
count++;
}
cout << "The value you want to search is at position " << count << endl;
}
void List::Delete(int da) {
Node *p = head, *q = head;
if (p == NULL) {
cout << "The List is Empty" << endl;
return;
}
while (p != NULL && p->data != da) {
q = p;
p = p->next;
}
q->next = p->next;
}
void List::Insert(int da) {
if (head == NULL) {
head = tail = new Node(da);
head->next = NULL;
tail->next = NULL;
}
else {
Node *p = new Node(da);
tail->next = p;
tail = p;
tail->next = NULL;
}
}
void List::print() {
Node *p = head;
while (p != NULL) {
cout << p->data << '\a';
p = p->next;
}
cout << endl;
}
int main() {
cout << "hello world" << endl;
List l1;
for (int i = 10; i < 17; i++) {
l1.Insert(i);
}
l1.print();
l1.Search(16);
l1.Delete(16);
l1.print();
l1.getValueAt(13);
l1.setValueAt(3, 9);
l1.print();
cout << "The End" << endl;
getchar();
return 0;
}
以上是关于c_cpp 链表类模板代码的主要内容,如果未能解决你的问题,请参考以下文章