2014-10-01 33 views
0

我有一個C程序,它創建了一個兩部分單向鏈表。
我使用結構來生成列表,節點和節點數據。 當結構被定義爲C結構段溢出

struct TList { 
    struct LNode* first; 
    struct LNode* last_left; 
}; 

struct LNode { 
    struct LData* data; 
    struct LNode* next; 
}; 

名單看​​起來像[ A B C ][ D E ] 其中, list->first = "A"list->last_left = "C"

下列功能重置鏈表光標。

void reset_list_cursor(struct TList *list) { 

    struct LNode *temp, *temp1, *temp2; 
    int i = (list_left_size(list) - 1); 

    for (i; i >= 0; i--) { 

     temp = list->last_left; 
     temp1 = list->first; 

     if (temp != NULL) { 

      temp2 = temp1->next; 
      while (temp2 != temp) { 
       temp1 = temp1->next; 
       temp2 = temp2->next; 
      } 

      list->last_left = temp1; 
     } 
    } 
    list->last_left = NULL; 
} 

但是,我得到一個分段錯誤,我已經把範圍縮小壽以下行...

void reset_list_cursor(struct TList *list) { 

    temp1 = temp1->next; 
    temp2 = temp2->next; 

我知道你永遠不能叫temp = temp->next->next,但是當你創建一個結構代替temp->next不應該工作嗎?

+6

如果知道temp和temp-> next不是NULL(或者更確切地說,已知是有效的),則'temp = temp-> next-> next;'在​​句法上是有效的並且是安全的。 。 – 2014-10-01 20:08:17

+1

這意味着你取消了'NULL'。先不檢查'NULL',你可以避免它。 – HuStmpHrrr 2014-10-01 20:25:50

+1

[MCVE](http://stackoverflow.com/help/mcve)會有所幫助。 – 2014-10-01 21:11:13

回答

0

首先,temp - > next - > next沒有問題,它的語法也是正確的。在涉及循環的任何情況下,你必須確保你在進入時確認「next」是否爲空。包括一個條件,當你進入循環時檢查temp - > next == NULL。這會爲你創造奇蹟。

這有點像while(temp1->next!=NULL && temp2->next!=NULL)

希望這有助於。