2013-02-22 43 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