编程实现:输入若干个正整数(输入-1为结束标志),建立一个单向链表,将其中的偶数值结点删除后输出。链表节点定义为: struct node{ int data; struct node *next; }
时间: 2023-04-30 13:03:47 浏览: 272
这段代码实现了一个单向链表,要求输入若干个整数(输入-1为结束标志),建立一个单向链表,将其中的偶数值节点删除后输出。链表节点定义为:struct node{ int data; struct node *next; }。
相关问题
编程实现:输入若干个正整数(输入-1为结束标志),建立一个单向链表,将其中的偶数值结点删除后输出。链表节点定义为: struct Node{ int data; struct Node *next; }
好的,以下是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
```
输入若干个正整数(输入-1为结束标志),建立一个单向链表,将其中的偶数值结点删除后输出。链表节点定义为: struct Node{ int data; struct Node *next; } 输入输出示例:括号内为说明 输入样例: 1 2 3 4 5 6 7 -1 输出样例: 1 3 5 7 用c语言写代码
好的,下面是代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *next;
};
void printList(struct Node *head) {
struct Node *p = head;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
void deleteEvenNodes(struct Node *head) {
struct Node *p = head, *q;
while (p != NULL && p->data % 2 == 0) {
head = p->next;
free(p);
p = head;
}
while (p != NULL) {
while (p != NULL && p->data % 2 == 1) {
q = p;
p = p->next;
}
if (p == NULL) break;
q->next = p->next;
free(p);
p = q->next;
}
}
int main() {
int x;
struct Node *head = NULL, *tail = NULL;
while (1) {
scanf("%d", &x);
if (x == -1) break;
struct Node *p = (struct Node *)malloc(sizeof(struct Node));
p->data = x;
p->next = NULL;
if (head == NULL) {
head = p;
tail = p;
} else {
tail->next = p;
tail = p;
}
}
printf("Original list: ");
printList(head);
deleteEvenNodes(head);
printf("List after deleting even nodes: ");
printList(head);
return 0;
}
```
代码的逻辑是先删除头部的所有偶数节点,然后再删除后面的偶数节点。需要注意的是,删除节点时要使用 `free` 函数释放内存,否则会出现内存泄漏的问题。
阅读全文