用C语言来写如果返回值为1,就输出新的链表;返回值为0,就输出没有变化
时间: 2023-05-22 20:07:00 浏览: 38
的链表,该怎么写?
你可以用以下代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
int changeList(Node **head) {
int result = 0;
// some code to modify the linked list
if (/* the linked list is modified */) {
result = 1;
}
return result;
}
void printList(Node *head) {
Node *currentNode = head;
while (currentNode != NULL) {
printf("%d ", currentNode->data);
currentNode = currentNode->next;
}
printf("\n");
}
int main() {
// create a linked list
Node *head = (Node *)malloc(sizeof(Node));
head->data = 1;
head->next = NULL;
Node *currentNode = head;
for (int i = 2; i <= 5; i++) {
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->data = i;
newNode->next = NULL;
currentNode->next = newNode;
currentNode = newNode;
}
// print the original linked list
printf("Original linked list: ");
printList(head);
// change the linked list and check the return value
int returnValue = changeList(&head);
// print either the modified or the original linked list
printf("Modified linked list: ");
if (returnValue == 1) {
printList(head);
} else {
printList(head);
}
return 0;
}
```
如果 `changeList()` 返回值为 1,即链表已经被修改,那么就输出修改过的链表;否则,就输出原来的链表。在 `main()` 函数中,我们创建了一个包含 5 个结点的链表,打印了原来的链表,然后调用 `changeList()` 函数来修改它,并根据返回值来输出修改后的链表或者原来的链表。