2013-02-22 74 views
-1

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

---->我知道问题在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); 
} 
+0

请让你的标题描述问题。 – 2013-02-22 18:04:03

回答

1

正如你的addString函数中提到的eduffy,你应该做一个比较而不是一个任务。另一个问题是设置currentNode->nextcurrentNode->previous。在你的printAll()函数中迭代,直到currentNode == NULL,它给出currentNode->next = current node你将有一个无限循环。直到您有超过1个元素,请将currentNode->next/previous作为NULL

1

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

顺便说一句,因为它看起来像刚刚开始使用C,请在编译器标志中调出警告。在修复所有警告之前,请勿运行您的代码。

+0

然后询问如何通过手动/谷歌找出如何使用编译器打开警告。对于gcc,使用开关:-Wall -Wextra – hyde 2013-02-22 18:09:52