为一个不定长多维数字信号设计一个链表,并实现对其进行基本操作,包括初始化、求 数据元素个数操作、插入、删除、取数据元素、判非空 ,均值滤波、上采样和下采样
时间: 2024-01-31 08:04:47 浏览: 76
链表节点定义如下:
```c++
typedef struct node {
double data;
struct node *next;
} Node;
```
链表操作函数定义如下:
```c++
/**
* 初始化链表
* @param head 链表头
*/
void initList(Node *&head) {
head = new Node;
head->next = nullptr;
}
/**
* 求链表长度
* @param head 链表头
* @return 链表长度
*/
int getListLength(Node *head) {
int len = 0;
Node *p = head->next;
while (p != nullptr) {
len++;
p = p->next;
}
return len;
}
/**
* 插入数据元素
* @param head 链表头
* @param data 要插入的数据元素
* @param pos 插入位置
* @return 插入是否成功
*/
bool insertList(Node *&head, double data, int pos) {
int len = getListLength(head);
if (pos < 1 || pos > len + 1) {
return false;
}
Node *p = head;
for (int i = 1; i < pos; i++) {
p = p->next;
}
Node *newNode = new Node;
newNode->data = data;
newNode->next = p->next;
p->next = newNode;
return true;
}
/**
* 删除数据元素
* @param head 链表头
* @param pos 删除位置
* @return 删除是否成功
*/
bool deleteList(Node *&head, int pos) {
int len = getListLength(head);
if (pos < 1 || pos > len) {
return false;
}
Node *p = head;
for (int i = 1; i < pos; i++) {
p = p->next;
}
Node *q = p->next;
p->next = q->next;
delete q;
return true;
}
/**
* 取数据元素
* @param head 链表头
* @param pos 取出位置
* @param data 取出的数据元素
* @return 取出是否成功
*/
bool getData(Node *head, int pos, double &data) {
int len = getListLength(head);
if (pos < 1 || pos > len) {
return false;
}
Node *p = head->next;
for (int i = 1; i < pos; i++) {
p = p->next;
}
data = p->data;
return true;
}
/**
* 判断链表是否为空
* @param head 链表头
* @return 是否为空
*/
bool isListEmpty(Node *head) {
return head->next == nullptr;
}
/**
* 均值滤波
* @param head 链表头
* @param window 窗口大小
* @return 滤波后的链表头
*/
Node *meanFilter(Node *head, int window) {
Node *newHead;
initList(newHead);
int len = getListLength(head);
if (window > len) {
window = len;
}
for (int i = 1; i <= len; i++) {
double sum = 0;
int count = 0;
for (int j = i - window / 2; j <= i + window / 2; j++) {
double data;
if (getData(head, j, data)) {
sum += data;
count++;
}
}
double mean = sum / count;
insertList(newHead, mean, i);
}
return newHead;
}
/**
* 上采样
* @param head 链表头
* @param factor 上采样因子
* @return 上采样后的链表头
*/
Node *upSample(Node *head, int factor) {
Node *newHead;
initList(newHead);
int len = getListLength(head);
for (int i = 1; i <= len; i++) {
double data;
if (getData(head, i, data)) {
insertList(newHead, data, i);
for (int j = 2; j <= factor; j++) {
insertList(newHead, data, i + (j - 1) * len);
}
}
}
return newHead;
}
/**
* 下采样
* @param head 链表头
* @param factor 下采样因子
* @return 下采样后的链表头
*/
Node *downSample(Node *head, int factor) {
Node *newHead;
initList(newHead);
int len = getListLength(head);
for (int i = 1; i <= len; i += factor) {
double data;
if (getData(head, i, data)) {
insertList(newHead, data, getListLength(newHead) + 1);
}
}
return newHead;
}
```
阅读全文