要求实现两个函数,分别将读入的数据存储为单链表、将链表中奇数值的结点重新组成一个新的链表
时间: 2023-03-28 12:00:35 浏览: 144
单链表的定义以及存储实现
好的,我可以回答这个问题。以下是两个函数的实现:
1. 将读入的数据存储为单链表:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
} Node;
Node *createList() {
Node *head = NULL, *tail = NULL;
int num;
while (scanf("%d", &num) == 1) {
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->data = num;
newNode->next = NULL;
if (head == NULL) {
head = tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
}
return head;
}
```
2. 将链表中奇数值的结点重新组成一个新的链表:
```c
Node *getOddList(Node *head) {
Node *oddHead = NULL, *oddTail = NULL;
Node *p = head;
while (p != NULL) {
if (p->data % 2 == 1) {
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->data = p->data;
newNode->next = NULL;
if (oddHead == NULL) {
oddHead = oddTail = newNode;
} else {
oddTail->next = newNode;
oddTail = newNode;
}
}
p = p->next;
}
return oddHead;
}
```
希望这可以帮助你!
阅读全文