gpt4 book ai didi

C——链表

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

我有 3 个文件 - String(用于获取字符并将它们组装成字符串(作为指针,但不是数组))、LinkedList 文件和 main(测试文件)。字符串部分工作正常,经过测试。但我卡在了 LinkedList 上。

----> 我知道问题出在 addString() 方法中,这是逻辑上的问题,因为我在它的末尾放置了一个打印检查,但我从未到达那里。但我似乎没有发现任何逻辑问题...这是 LinkedList 的代码:

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

struct node
{
struct node *next;
struct node *previous;
struct string *str;
};

static struct node *head;
static struct node *tail;

int count = 0;

void initList()
{
head = NULL;
tail = NULL;
}

void addString(struct string *str_)
{
struct node *current = malloc(sizeof(struct node));
if (head = NULL)
{
head = current;
tail = current;
current->next = tail;
current->previous = head;
current->str = str_;
}
else
{
current->previous = tail;
tail->next = current;
tail = current;
current->str = str_;
}

puts("\nA string has been added!");

}

void deleteString(int index)
{
struct node *currentNode;
currentNode = head;
int i = 0;

if(index == 0)
{
head->str = NULL;
head->next = head;
// delete first node and relocate "head" to next node
}
while(currentNode != NULL)
{
if(i == index)
{
currentNode->str = NULL;
currentNode->previous->next = currentNode->next;
currentNode->next->previous = currentNode->previous;
}
else
{
currentNode = currentNode->next;
i++;
}
// 1.loop through and starting from 0 as first (head) element
// 2.when index is reached - delete it and replace the connections
}
}

void printAll()
{
struct node *currentNode;
currentNode = head;

while(currentNode !=NULL)
{
printf("%s", currentNode->str);
currentNode = currentNode->next;
}// need to iterate through list
}

这是测试文件:

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

#include "String.h"
#include "LinkedList.h"

int main(int argc, char** argv) {

initList();

char* c;
c = getChars();

struct string *strp1;
strp1 = malloc(sizeof(struct string));
strp1 = make_string(c);
addString(strp1);
printAll();

printf("%s", *strp1);
puts("\nsome text");
return (EXIT_SUCCESS);
}

最佳答案

正如 eduffy 在您的 addString 函数中提到的,您应该进行比较而不是赋值。另一个问题是设置 currentNode->nextcurrentNode->previous。在 printAll() 函数中,您将迭代直到 currentNode == NULL,鉴于 currentNode->next = current Node 您将拥有无限个环形。将 currentNode->next/previous 保留为 NULL,直到拥有超过 1 个元素。

关于C——链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15030362/

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