gpt4 book ai didi

c - 反向打印双向链表,仅打印第一个元素

转载 作者:行者123 更新时间:2023-11-30 18:33:30 26 4
gpt4 key购买 nike

编写一个函数来反向打印双向链表。该功能仅在打印 7 后停止,并且不会打印列表中的其余项目。我的程序和功能如下。

已编辑以包含未粘贴的代码。使用 Putty 进行复制和粘贴时遇到问题,我深表歉意。

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

struct node
{
int data;
struct node *next;
struct node *prev;
};
typedef struct node node;


void printRev(node* head);
node* removeNode(node* head, int d);
node* insertFront(node* head, int d);
node* insertBack(node* head, int d);
void print(node* head);
int max(node* head);
int min(node* head);
int locInList(node* head, int x);

int main()
{

node* head = NULL;

head = insertFront(head, 5);
head = insertFront(head, 4);
head = insertBack(head, 6);
head = insertBack(head, 7);
print(head);
printRev(head);

printf("Max: %d\n", max(head));
printf("Min: %d\n", min(head));
printf("locInList 5: %d\n", locInList(head, 5));
printf("locInList 9: %d\n", locInList(head, 9));

head = removeNode(head, 6);
print(head);
head = removeNode(head, 4);
print(head);
head = removeNode(head, 7);
print(head);


return 0;
}

void printRev(node* head) {
node *cur = head;
node *tmp = NULL;
if (cur == NULL) {
return;
}
else {
while(cur->next != NULL) {
cur = cur->next;
}
while(cur != NULL) {
printf("%d ", cur->data);
cur = cur->prev;
}
}
printf("\n");
}

node* removeNode(node* head, int d)
{

node *tmp = head->next;
head->data = head->next->data;
head->next = tmp->next;
free(tmp);
return head;
}

node* insertFront(node* head, int d)
{
node *tmp = NULL;
tmp = malloc(sizeof(node));
tmp->data = d;
tmp->next = head;
head = tmp;
return head;
}

node* insertBack(node* head, int d)
{
node *tmp = malloc(sizeof(node));

tmp->data = d;
tmp->next = NULL;

if(head == NULL){
return head;
}
}
else{
node *end = head;

while(end->next != NULL){
end = end->next;
}
end->next = tmp;
}

return head;


}

void print(node* head)
{

node *tmp = head;

while(tmp != NULL){
printf("%d ", tmp->data);
tmp = tmp->next;
}
printf("\n");
}

int max (node* head)
{

int max = head->data;
node *tmp = NULL;
tmp = head;


while(tmp->next != NULL){
if(tmp->data >= max){
max = tmp->data;
}
tmp = tmp->next;
}
}
return min;
}

int locInList(node* head, int x)
{

int i = 0;
node *tmp = NULL;
tmp = head;

while(tmp != NULL){
if(tmp->data == x){
return i;
}else{
i++;
tmp = tmp->next;
} }
return -1;

}

预期结果是 - 7 6 5 4收到的结果是 - 7

最佳答案

insertFrontinsertBack 都没有设置 prev,这是问题的根本原因。 (您的反向迭代循环关键取决于是否正确设置了 prev 指针。)

关于c - 反向打印双向链表,仅打印第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57029917/

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