gpt4 book ai didi

c - 使用嵌套 while 循环反转链表

转载 作者:行者123 更新时间:2023-11-30 21:28:30 25 4
gpt4 key购买 nike

我需要一些帮助。

我的家庭作业将于周三到期,我唯一无法做的就是反转我的链接列表。我实际上一整天都在研究这个问题。

我的教授没有告诉我们任何方法可以做到这一点,也不允许我们通过电子邮件向他发送问题,所以我有点陷入困境。

他希望我们通过使用嵌套的 while 循环以及称为 front 和 back 以及 newhead 的指针来完成此任务。

下面是我的代码。如果您有任何疑问,请告诉我,并提前致谢。

注意:代码是使用 GNU 编译器在 Code::Blocks 中编译的。

#include <stdio.h>
#include <stdlib.h>

typedef struct node {
int random_number;
struct node *next;
} Node;

typedef Node *Nodeptr;

void printout(Nodeptr);
void sum(Nodeptr);
void reverse(Nodeptr);

int main() {
Nodeptr head = NULL;

if ((head = malloc(sizeof(Node))) == NULL)
return 0;
head->random_number = rand() % 50 + 50;
head->next = NULL;

Nodeptr here = head;
Nodeptr newnode = NULL;
int n;

for (n = 0; n < 10; n++) {
if ((newnode = malloc(sizeof(Node))) == NULL)
return 0;
newnode->random_number = rand() % 50 + 50;
newnode->next = NULL;
here->next = newnode;
here = here->next;
}
printout(head);
sum(head);
reverse(&head);
printout(head);

return 0;
}

void printout(Nodeptr head) {
Nodeptr aux = head;
int n = 0;
while (aux != NULL) {
printf("The value of node no. %d is %d \n", n, aux->random_number);
aux = aux->next;
n++;
}
}

void sum(Nodeptr head) {
Nodeptr aux = head;
int n = 0, sum = 0;
while (aux != NULL) {
sum += aux->random_number;
aux = aux->next;
n++;
}
printf("The sum total of all nodes in this list is %d\n", sum);
}

void reverse(Nodeptr head) {
Nodeptr newhead = head;
Nodeptr back = NULL;
Nodeptr front = NULL;

while (back != NULL) {
front->next = back;
back = NULL;
front = head->next;
back = head;
while (front != NULL) {
front = newhead->next;
newhead->next = back;
back = newhead;
}
newhead = head;
}
}

最佳答案

如果反转链接列表:

A -> B -> C -> D -> E (odd numbered case)
E -> D -> C -> B -> A

A -> B -> C -> D (even numbered case)
D -> C -> B -> A

你看到这些元素的位置发生了怎样的变化吗?在奇数情况下,A 与 E 交换位置,B 与 D 交换位置,C 没有移动。

现在你知道如何通过循环来做到这一点吗?外循环从列表的开头到中间点,内循环找到匹配的项来交换它们。

绝对不是反转链表的最有效方法,但我想这只是让您更多地思考数据结构的一种方法。

您发布的reverse()没有意义,因为指针值不正确。当 back 初始化为 NULL 时,while 循环根本不会执行。

关于c - 使用嵌套 while 循环反转链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40735276/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com