gpt4 book ai didi

c - 如何在 C 中反转单链表?

转载 作者:行者123 更新时间:2023-12-02 06:54:20 25 4
gpt4 key购买 nike

对于我的类(class),我的任务是构建链表、输入数据和执行不同的功能。我的代码编译正常,但是还原和建设性还原功能不起作用。

如果我反转列表并打印它,我只会得到第一个节点。我似乎在某处错过了重点。这是我的代码:(如果您发现任何其他功能有任何错误,请告诉我)提前致谢!

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

typedef struct DoubleNode{
struct DoubleNode* next;
double data;

} DoubleNode;

DoubleNode* insertFirst(DoubleNode*head, double c) {
DoubleNode* temp;
temp=malloc(sizeof(DoubleNode));
temp->data= c;
temp->next= head;

return temp;
}
void printList(DoubleNode*head) {
DoubleNode* cursor;
printf("(");
cursor=head;
while (cursor != NULL) {
printf("%fl", cursor->data);
printf(" ");
cursor=cursor->next;
}
printf(")");
}


DoubleNode* insertLast(DoubleNode *head, double d) {
DoubleNode *tmp, *cursor;
//trivial case: empty list
if (head==NULL)
{return insertFirst(head,d);
} else{
//general case: goto end
cursor=head;
while (cursor->next != NULL){
cursor =cursor->next;
}
tmp= malloc(sizeof(DoubleNode));
tmp->data = d;
tmp->next = NULL;
cursor->next=tmp;
return head;
}
}

DoubleNode* reverseDoubleListCon(DoubleNode*head) {
DoubleNode *temp, *res, *cell;
cell=head;
res=NULL;
while (cell!=NULL) {
temp=malloc(sizeof(DoubleNode));
temp->data=cell->data;
temp->next=res;
res=temp;
cell=cell->next;
}
return res;
}

void reverseDoubleList(DoubleNode*head) {
DoubleNode *chain, *revChain, *cell;
cell=head;
revChain=NULL;
while (cell!=NULL) {
chain=cell->next;
cell->next=revChain;
revChain=cell;
cell=chain;
}
head=revChain;
}

double get(DoubleNode*head, double n) {
DoubleNode *cursor;
cursor=head;
for (int i=0; i<n; i++) {
cursor=cursor->next;

}
return cursor->data;
}

DoubleNode* delete(DoubleNode*head, double n) {
DoubleNode *cursor, *rest;
cursor=head;
for (int i=0; i<n; i++) {
cursor=rest;
cursor=cursor->next;

}
rest->next=cursor->next;
free(cursor);
return head;

}

DoubleNode* insert(DoubleNode*head, double d, double n) {
DoubleNode *cursor, *temp, *rest;
cursor=head;

for (int i = 0; i<n-1; i++) {
rest=cursor;
cursor= cursor->next;
}
temp=malloc(sizeof(DoubleNode));
temp->data=d;
temp->next=cursor;
rest->next= temp;

return head;
}

int main(int argc, const char * argv[]) {
DoubleNode *head;
head=malloc(sizeof(DoubleNode));

for (double i=0.0; i <11.0; i++) {
head=insertLast(head, i);
}
printList(head);
reverseDoubleList(head);
printList(head);
reverseDoubleListCon(head);
printList(head);

return 0;
}

最佳答案

void rev(node **head)
{
node *prev = NULL;
node *next = *head->next;
node *cur;

for (cur = *head; cur; cur = next) {
next = cur->next;
prev = cur;
}
*head = prev
}

首先是链表: enter image description here


第二步:让节点B指向A,让A->next为NULL enter image description here
第 3 步:该过程继续...... enter image description here
第 4 步:链表现在反转了。 enter image description here

关于c - 如何在 C 中反转单链表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34840059/

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