1.
【描述】
给定一个链表,链表的每个节点只含有一个int型元素和Node*指针,该链表共有十个节点,输出链表元素值为奇数的项。部分代码已经写好,请补全output函数即可。
【输入】
输入10个整数。
【输出】
输出奇数值,以空格隔开。
【输入示例】
1 3 4 5 6 7 8 10 11 15
【输出示例】
1 3 5 7 11 15
#include <iostream>
using namespace std;
class Node {
public:
int value;
Node *next;
Node() { }
Node(int x) : value(x), next(NULL) { }
};
class SingleLinkedList {
public:
SingleLinkedList() {
head = NULL;
}
void init() { // 链表初始化
int val;
cin >> val;
head = new Node(val);
Node *tmpNode = head;
for(int i = 0; i < 9; i++) { // 链表共有10个节点,head后还有9个
cin >> val;
Node *pNode = new Node(val);
tmpNode->next = pNode;
tmpNode = pNode;
}
tmpNode->next = NULL;
}
void output() { // 输出链表
/* 请在此处编写相关代码 */
Node *current = head; // 从头节点开始遍历
bool first = true;
while (current != NULL) {
if (current->value % 2 != 0) {
if (!first) {
cout << " ";
}
cout << current->value;
first = false;
}
current = current->next;
}
cout << endl;
}
private:
Node *head;
};
int main() {
SingleLinkedList list;
list.init();
list.output();
return 0;
}
2.
【描述】
编写程序,输入若干个正整数,输入-1时输入结束,可以简化修改本章教材提供的链表类LinkedList,用单向链表组织输入的正整数。要求链表按照结点中整数值的大小从大到小排序,不包括最后标识结束的-1。输出单向链表。
【输入】
一系列正整数,输入-1表示结束,-1不是输入的数据的一部分。
【输出】
按照结点中整数值的大小从大到小输出所有的整数,每个整数后面跟一个空格以与后面的整数区分,最后的整数后面没有空格。
【输入示例】
1 3 5 2 -1
【输出示例】
5 3 2 1
#include <iostream>
using namespace std;
/* 请在此处编写LinkedList类 */
template <typename T>
class Node {
public:
T value;
Node *next;
Node(T val) : value(val), next(nullptr) {}
};
template <typename T>
class LinkedList {
public:
LinkedList() : head(nullptr) {}
void add(T val) {
Node<T>* newNode = new Node<T>(val);
if (!head || head->value < val) {
newNode->next = head;
head = newNode;
} else {
Node<T>* current = head;
while (current->next && current->next->value >= val) {
current = current->next;
}
newNode->next = current->next;
current->next = newNode;
}
}
void print() {
Node<T>* current = head;
while (current) {
cout << current->value;
current = current->next;
if (current) cout << " ";
}
cout << endl;
}
private:
Node<T>* head;
};
int main() {
LinkedList<int> list;
int num;
cin >> num;
while(num > 0) {
list.add(num); // 输入的正整数按从大到小的顺序添加到链表中
cin >> num;
}
list.print(); // 输出链表
return 0;
}