C ++程序使用链表实现行程编码
在本教程中,我们将讨论一个程序,该程序使用链接列表来实现游程长度编码。
为此,我们将提供一个链表。我们的任务也使用运行长度编码对链接列表的元素进行编码。
例如,如果链接列表的元素是“a->a->a->a->a”,则在游程长度编码中,它们将被替换为“a→5”。
示例
#include <bits/stdc++.h>
using namespace std;
//structuring linked list node
struct Node {
char data;
struct Node* next;
};
//creating a new node
Node* newNode(char data){
Node* temp = new Node;
temp->data = data;
temp->next = NULL;
return temp;
}
//adding nodes to the list
void add_node(struct Node* head_ref, char new_data){
struct Node* new_node = newNode(new_data);
struct Node* last = head_ref;
if (head_ref == NULL) {
head_ref = new_node;
return;
}
while (last->next != NULL)
last = last->next;
last->next = new_node;
return;
}
void print_llist(Node* node){
while (node != NULL) {
cout << node->data << " ";
node = node->next;
}
}
//encoding the given list
void llist_encode(Node* head){
Node* p = head;
Node* temp = newNode(p->data);
char c = p->data;
p = p->next;
int count = 1;
while (p != NULL) {
char x = p->data;
if (c == x)
count++;
else {
if (count > 1) {
if (count > 9)
add_node(temp, '0' + (count / 10));
add_node(temp, '0' + (count % 10));
}
count = 1;
add_node(temp, x);
c = x;
}
p = p->next;
}
if (count != 0)
add_node(temp, '0' + count);
print_llist(temp);
}
int main(){
Node* head = newNode('a');
head->next = newNode('a');
head->next->next = newNode('b');
head->next->next->next = newNode('b');
head->next->next->next->next = newNode('r');
head->next->next->next->next->next = newNode('r');
llist_encode(head);
return 0;
}输出结果
a 2 b 2 r 2
热门推荐
1 狗狗技能训练
5 如何训练狗狗笑
6 狗狗训练排便
9 狗狗响片训练
10 如何训练狗狗不捡食
11 狗狗尿训练
12 怎么训练狗狗找东西
13 狗狗训练站立
14 狗狗训练飞盘
15 鞍山狗狗训练
16 怎样训练泰迪狗狗谢谢
17 狗狗外出训练
18 怎么训练金毛狗狗大小便