c - 反向打印双向链表仅打印第一个元素
问题描述
编写一个函数来反向打印一个双向链表。该功能仅在打印 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
解决方案
既不insertFront
是也不是insertBack
set prev
,这是您问题的根本原因。(您的反向迭代循环严重依赖于prev
正确设置的指针。)
推荐阅读
- python - 不是一个类 - TypeError: function() 接受 0 个位置参数,但给出了 1 个
- sql - SQL:如何获得足够的事件天数,使我至少有 50 个事件
- r - 我希望能够操纵“phylo”类中的对象 - 即。四舍五入/将我的引导值从小数 (.998) 转换为百分比 (99%)
- python - 修改后用匹配替换python中的子字符串
- eclipse - 使用 eGit 拉取带有已删除文件的分支
- excel - 如何测试是否设置了 Outlook,如果没有设置如何绕过
- dart - 将 Dart 2 Map 动态转换为 Javascript 对象
- elm - Elm 在 HTML 属性中放置打开的文本
- php - 从 mysql 数据库加载到 bootstrap 4 轮播中的图像
- c# - 可互换地处理存储在 BitVector32、int 和 uint 中的 32 位向量是否安全?