c++链表实现进程管理
时间: 2024-01-06 10:05:26 浏览: 74
以下是使用C++链表实现进程管理的示例代码:
```cpp
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
struct Process {
string proname;
int time, pri;
bool status;
};
struct Node {
Process val;
Node* next;
Node(Process x) : val(x), next(NULL) {}
};
class Linklist {
public:
Node* head;
Linklist();
void Insert(Process val, int pos);
void Remove(Process val);
void Print();
int Find(Process val);
int Length();
~Linklist();
private:
int length;
};
Linklist::Linklist() {
head = NULL;
length = 0;
}
void Linklist::Insert(Process val, int pos) {
if (pos < 0 || pos > length) {
cout << "Invalid position!" << endl;
return;
}
Node* newNode = new Node(val);
if (pos == 0) {
newNode->next = head;
head = newNode;
}
else {
Node* curr = head;
for (int i = 0; i < pos - 1; i++) {
curr = curr->next;
}
newNode->next = curr->next;
curr->next = newNode;
}
length++;
}
void Linklist::Remove(Process val) {
Node* curr = head;
Node* prev = NULL;
while (curr != NULL) {
if (curr->val.proname == val.proname) {
if (prev == NULL) {
head = curr->next;
}
else {
prev->next = curr->next;
}
delete curr;
length--;
return;
}
prev = curr;
curr = curr->next;
}
cout << "Process not found!" << endl;
}
void Linklist::Print() {
Node* curr = head;
while (curr != NULL) {
cout << "Process Name: " << curr->val.proname << endl;
cout << "Priority: " << curr->val.pri << endl;
cout << "Running Time: " << curr->val.time << endl;
cout << "Status: " << (curr->val.status ? "Running" : "Not Running") << endl;
cout << endl;
curr = curr->next;
}
}
int Linklist::Find(Process val) {
Node* curr = head;
int pos = 0;
while (curr != NULL) {
if (curr->val.proname == val.proname) {
return pos;
}
curr = curr->next;
pos++;
}
return -1;
}
int Linklist::Length() {
return length;
}
Linklist::~Linklist() {
Node* curr = head;
Node* next = NULL;
while (curr != NULL) {
next = curr->next;
delete curr;
curr = next;
}
}
int main() {
Linklist processList;
Process p1 = { "Process1", 10, 2, true };
Process p2 = { "Process2", 5, 1, false };
Process p3 = { "Process3", 8, 3, true };
processList.Insert(p1, 0);
processList.Insert(p2, 1);
processList.Insert(p3, 2);
processList.Print();
processList.Remove(p2);
processList.Print();
int pos = processList.Find(p3);
if (pos != -1) {
cout << "Process found at position: " << pos << endl;
}
else {
cout << "Process not found!" << endl;
}
return 0;
}
```
阅读全文