编写一个函数以反向打印双向链表。该功能仅在打印7之后停止,并且不打印列表中的其余项目。我的程序和功能如下。
已编辑以包含未粘贴的代码。对于在腻子复制和粘贴时遇到的问题,我深表歉意。
#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
答案 0 :(得分:2)
insertFront
和insertBack
都没有设置prev
,这是问题的根本原因。 (您的反向迭代循环严重取决于正确设置的prev
指针。)
答案 1 :(得分:1)
由于它是一个双向链接列表,因此您应该将头的后方指针指向函数insertFront中的temp(新插入的一个)。应该是;
node* insertFront(node* head, int
d)
{
node *tmp = NULL;
tmp = malloc(sizeof(node));
tmp->data = d;
tmp->prev=NULL:
if(head==NULL)
return tmp;
head->prev=tmp;
tmp->next = head;
return tmp;
}
类似地,在insertBack函数中,请注意使上一个指针指向列表中的上一个节点。