java写一个进程控制用单链表
时间: 2024-05-11 17:19:59 浏览: 16
以下是一个简单的Java单链表实现进程控制:
```java
class ProcessNode {
// 进程控制块的属性
int pid; // 进程ID
String name; // 进程名称
int priority; // 进程优先级
String status; // 进程状态
ProcessNode next; // 指向下一个进程
public ProcessNode(int pid, String name, int priority, String status) {
this.pid = pid;
this.name = name;
this.priority = priority;
this.status = status;
this.next = null;
}
}
class ProcessLinkedList {
private ProcessNode head; // 链表头,指向第一个进程
public ProcessLinkedList() {
this.head = null;
}
public void add(int pid, String name, int priority, String status) {
ProcessNode newNode = new ProcessNode(pid, name, priority, status);
if (head == null) {
head = newNode; // 如果链表为空,则把新节点设为头节点
return;
}
ProcessNode current = head;
while (current.next != null) {
current = current.next; // 找到链表的最后一个节点
}
current.next = newNode; // 把新节点插入到链表的末尾
}
public void remove(int pid) {
if (head == null) {
return; // 链表为空,直接返回
}
if (head.pid == pid) {
head = head.next; // 删除头节点
return;
}
ProcessNode current = head;
while (current.next != null) {
if (current.next.pid == pid) {
current.next = current.next.next; // 删除当前节点的下一个节点
return;
}
current = current.next;
}
}
public void display() {
ProcessNode current = head;
System.out.println("Process ID\tProcess Name\tPriority\tStatus");
while (current != null) {
System.out.println(current.pid + "\t\t" + current.name + "\t\t" + current.priority + "\t\t" + current.status);
current = current.next;
}
}
}
public class Test {
public static void main(String[] args) {
ProcessLinkedList processList = new ProcessLinkedList();
// 添加进程
processList.add(1001, "Process A", 1, "Running");
processList.add(1002, "Process B", 2, "Ready");
processList.add(1003, "Process C", 3, "Blocked");
// 显示进程列表
processList.display();
// 删除进程
processList.remove(1002);
// 再次显示进程列表
processList.display();
}
}
```
以上代码中,`ProcessNode`类表示进程控制块,包含了进程的各种属性,以及一个指向下一个进程的指针。`ProcessLinkedList`类表示单链表,包含了链表的各种操作,如添加进程、删除进程和显示进程列表等。在`main`方法中,我们先创建一个空的进程列表,然后添加三个进程,再显示进程列表,最后删除一个进程,再次显示进程列表。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)