-1

我有 3 个文件 - 字符串(用于获取字符并将它们组合成字符串(作为指针,但不是数组))、LinkedList 文件和主文件(测试文件)。字符串部分工作正常,已经过测试。但我被困在 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);
}
4

2 回答 2

1

(head = NULL)是赋值语句,而不是比较。将其更改为(head == NULL).

顺便说一句,因为看起来你刚刚开始使用 C,所以在编译器标志中打开警告。在修复所有警告之前不要运行代码。

于 2013-02-22T18:02:28.950 回答
1

正如您的addString函数中提到的eduffy,您应该进行比较而不是分配。另一个问题是设置currentNode->nextcurrentNode->previous。在您的printAll()函数中,您迭代 until currentNode == NULL,因为currentNode->next = current node您将有一个无限循环。保持currentNode->next/previous原样,NULL直到您拥有超过 1 个元素。

于 2013-02-22T18:06:09.943 回答