我試圖列印存盤在一個鏈接串列中的值,但我遇到了一個無限回圈。請有人告訴我我的代碼有什么問題。我能夠成功地收集節點的資料,但在列印串列時,我遇到了一個連續的回圈。如果有任何幫助,我將不勝感激。預先感謝
struct node {
int data; /4 bytes
struct node *next; // 4bytes 32 bit and 8 bytes i 64bit cp
};
int main(){
struct node *head, *newnode, *temp;
head = NULL ;
temp = head;
int count=0, choice=1;
while(choice){
newnode = (struct node *)malloc(sizeof(struct node) )。)
printf("enter data:")。
scanf("%d",&newnode-> data)。
newnode->next = head;
if(head == 0) {
head = temp = newnode。
}
else{
temp-> next = newnode;
temp = newnode;
}
printf(" %d ",temp->data)。
printf("Do you want to continue? 0/1") 。
scanf("%d",&choice)。
}
int i = 0;
temp = head;
while( temp!=NULL){
printf("%d", temp->data)。
temp=temp->接下來。
}
}
uj5u.com熱心網友回復:
當你創建一個新的節點時,你將它的 "下一個 "節點設定為頭部節點。這就是回圈的方式。 把它設定為NULL。
之后,你將新節點設定為 "當前節點的下一個節點",同時也設定為 "當前節點"。 我相信你想把它設定為temp的下一個節點,然后把temp移到它的下一個節點。
另外,請不要將 head 與 0 進行比較...... 如果你希望它是NULL,請與NULL比較。
uj5u.com熱心網友回復:
我懷疑這是否在有關作業問題的范圍內,但將鏈表任務分解成小問題確實很有幫助。
我們從這個節點的定義開始:
struct node {
int data; /4 bytes
struct node *next; // 4bytes 32 bit and 8 bytes i 64bit cp
};
我將對其進行型別化定義,以使我的生活稍微輕松一些。
typedef struct node {
int data; /4 bytes
struct node *next; // 4bytes 32 bit and 8 bytes i 64bit cp
} node_t;
讓我們為一個給定的頭找到最后一個節點。我們將創建一個node_t指標,稱為current,并使用它來行走串列,直到它在最后一個節點。我們將知道它是最后一個,因為它的next成員將是NULL。當然,如果head是NULL,那么我們將立即回傳NULL。
node_t *last_node(node_t *head) {
if (head == NULL) {
return NULL。
}
node_t *current;
for (current = head; current->next != NULL; current = current-> next);
return current。
}
現在,讓我們向一個具有給定頭部的串列添加一個值。我們可以通過回傳一個新的最后一個節點的指標來提供一個捷徑。如果head是NULL的話,我們也將縮短大量的作業。
否則,我們將使用我們定義的last_node函式獲得最后一個節點,將其next設定為新節點,并回傳一個指向新節點的指標。
node_t *add_to_list(node_t *head, int value) {
node_t * new_node = malloc(sizeof(node_t) 。)
new_node->data = value;
new_node->next = NULL;
if (head == NULL) {
return new_node;
}
node_t *last = last_node(head);
last->next = new_node;
return new_node;
}
最后我們可以寫一個函式來列印這個串列。鑒于你已經看到了行走的串列,這看起來應該很熟悉。
void print_list(node_t *head) {
for (node_t *current = head;
current->next != NULL;
current = current->next) {
printf("%d", current->data) 。
}
}
將大問題分解成小問題是至關重要的。練習一下吧!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/322478.html
標籤:
上一篇:每當httpapi中的angular發生錯誤時,是否有任何方法可以路由到錯誤頁面?
下一篇:在C/C 宏定義的開頭粘貼標記
