编程实现:输入若干个正整数(输入-1为结束标志),建立一个单向链表,将其中的偶数值结点删除后输出。链表节点定义为: struct Node{ int data; struct Node *next; }
时间: 2024-03-26 20:40:45 浏览: 125
好的,以下是C++代码实现:
```
#include <iostream>
using namespace std;
struct Node{
int data;
struct Node* next;
};
void deleteEvenNodes(Node* head){
Node* current = head;
Node* prev = NULL;
while(current != NULL){
if(current->data % 2 == 0){
if(prev == NULL){
head = current->next;
delete current;
current = head;
}
else{
prev->next = current->next;
delete current;
current = prev->next;
}
}
else{
prev = current;
current = current->next;
}
}
}
void printList(Node* head){
Node* current = head;
while(current != NULL){
cout << current->data << " ";
current = current->next;
}
cout << endl;
}
int main(){
Node* head = NULL;
Node* tail = NULL;
int data;
cout << "请输入若干个正整数,以-1结束:" << endl;
cin >> data;
while(data != -1){
Node* newNode = new Node;
newNode->data = data;
newNode->next = NULL;
if(head == NULL){
head = newNode;
tail = newNode;
}
else{
tail->next = newNode;
tail = newNode;
}
cin >> data;
}
deleteEvenNodes(head);
printList(head);
return 0;
}
```
输入样例:
```
请输入若干个正整数,以-1结束:
1 2 3 4 5 6 -1
```
输出样例:
```
1 3 5
```
阅读全文