正如eduffy在
我有三个文件-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);
}
addString
函数中提到的那样,应该进行比较而不是赋值。另一个问题是设置currentNode->next
和currentNode->previous
。在printAll()
函数中,您可以迭代到currentNode == NULL
,如果是currentNode->next = current node
,您将有一个无限循环。将currentNode->next/previous
保留为NULL
,直到您有多个元素为止。
(head = NULL)
是一个赋值语句,而不是比较。将其更改为(head == NULL)
。
顺便说一句,因为看起来你刚从C开始,所以在编译器标志中打开警告。在修复所有警告之前,不要运行代码。