2013-02-27 81 views
0

我有兩個結構體名稱* head和* tail。正在搜索一個項目鏈表C(隊列)

我用頭開始鏈表和尾部。

可以說我有元素

typedef struct queue 
{ 
    int stuff; 
    struct queue *nextNode; 
}q; 

在我的節點,東西一個任意數量的鏈表= 164(這是假設)

我怎麼會去通過搜索我的鏈表找到164?

謝謝!

+0

迭代:檢查第一個。如果它是164,你就完成了。否則檢查下一個節點(除非是NULL)。 – wildplasser 2013-02-27 22:33:43

回答

5

搶指針鏈表的頭。假設在列表中的最後一個項目都標有nextNode指針是NULL,您可以通過一個在列表中一個循環:

struct queue *tmp = head; 
while (tmp != NULL) { 
    if (tmp->stuff == 164) { 
     // found it! 
     break; 
    } 
    tmp = tmp->nextNode; 
} 
+0

非常感謝。完美的感覺! – juice 2013-02-27 22:49:32

0

在您的隊列只是想迭代

struct queue *current = head; 

while(current != NULL) 
{ 
    if(current->stuff == numToSearch) 
     // found it 
    current = current->nextNode; 

} 

注:原諒任何輕微的語法錯誤,它已經有一段時間,因爲我已經觸及Ç

+0

這還不是C. – 2013-02-27 22:35:34

+0

我們越來越近了。 – 2013-02-27 22:37:16

0
struct queue *find(struct queue *ptr, int val) { 
for (; ptr; ptr = ptr->nextNode) { 
    if (ptr->stuff == val) break; 
    } 
return ptr; 
} 
0

開始頭。雖然沒有達到尾巴和當前項目的價值不是我們正在尋找去下一個節點。如果項目完成循環不是我們正在尋找的 - >這樣的項目不存在於列表中。代碼是在假定尾指針不是NULL的情況下編寫的。

struct queue* item = head; 
while (item != tail && item->stuff != 164) { 
    item = item->nextNode; 
} 
if (164 == item->stuff) { 
// do the found thing 
} else { 
// do the not found thing 
} 
+0

圍繞該代碼的解釋一詞將受到歡迎。 – joce 2013-02-27 23:31:36