gpt4 book ai didi

C删除函数中的循环双向链表

转载 作者:行者123 更新时间:2023-12-04 08:58:57 26 4
gpt4 key购买 nike

我有一个循环双向链表。deletefront()功能不工作:输出错误。什么是错误?
其他功能正在运行。但是我在调​​用 deletefront 后显示后得到错误的输出功能。应该删除的 100 值仍然出现。请更正。
我已经包含了 C 源代码:

// circular doubly linked list
#include <stdio.h>
#include <stdlib.h>

typedef struct node {
int data;
struct node *rlink;
struct node *llink;
} node;

node *head = NULL;

node *getnode(int ele) {
node *ptr;
ptr = (node *)malloc(sizeof(node));
if (ptr == NULL) {
printf("memory not alloc");
exit(0);
}
if (ptr != NULL) {
ptr->data = ele;
ptr->rlink = NULL;
ptr->llink = NULL;
}
return ptr;
}

void insertfront(int ele) {
node *newnode;
newnode = getnode(ele);
if (head == NULL) {
head = newnode;
head->rlink = head;
head->llink = head;
} else {
head->llink = newnode;
newnode->rlink = head;
head = newnode;
}
}

void insertend(int ele) {
node *newnode;
newnode = getnode(ele);
if (head == NULL) {
head = newnode;
head->rlink = head;
head->llink = head;
} else {
node *temp = head;
do {
temp = temp->rlink;
} while (temp != head->llink);

newnode->rlink = temp->rlink;
temp->rlink = newnode;
newnode->llink = temp;
}
}

int lenlist() {
node *temp;
int count = 0;
temp = head;
do {
temp = temp->rlink;
count++;
} while (temp != head);

return count;
}

void insertatpos(int ele,int pos) {
if (pos == 1) {
insertfront(ele);
} else
if (pos == (lenlist() + 1)) {
insertend(ele);
} else
if (pos > 1 && pos <= (lenlist() + 1)) {
node *prev, *curr;
node *newnode = getnode(ele);
int count = 1;
curr = head;//curr points to 1st node
do {
prev = curr;
count++;
curr = curr->rlink;
if (count == pos) {
prev->rlink = newnode;
newnode->llink = prev;
newnode->rlink = curr;
curr->llink = newnode;
}
} while (curr != head);
} else {
printf("invalid position");
}
}

void delfront() {
if (head == NULL)
printf("empty list");

node *aux;
node *lastnode, *secondnode;
aux = head;
lastnode = head->llink;
secondnode = head->rlink;

secondnode->llink = lastnode;
lastnode->rlink = secondnode;

free(aux);

head = secondnode;
}

void display() {
node *aux = head;
do {
printf("%d->", aux->data);
aux = aux->rlink;
} while (aux != head);
printf("\n");
}

int main() {
insertfront(100);
insertend(20);
printf("\n%d\n", lenlist());
insertatpos(45, 2);
display();
delfront();
display();
}

最佳答案

问题不在deletefront()功能,相反,您错过了更新 insertfront() 中的一些链接。和 insertend()职能。
我已经更新了代码 here并在我进行更改的地方添加了评论。尝试使用示例对其进行可视化。
但是,我建议您使用调试器解决此类问题,或者使用示例测试用例查看代码。它将提高您的调试和编码技能!

关于C删除函数中的循环双向链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63655081/

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