[英]Single Linked List print in order of for loop
我試圖按照在鏈表中創建每個節點的順序打印鏈表。 例如,它應該打印出“ 0 1 2 3 4”,但是我的代碼是錯誤的,什么也沒打印出來。 我認為問題出在我的for循環中。
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
int main(void)
{
struct node *head = NULL;
struct node *tail = NULL;
struct node *current;
current = head;
int i;
for(i = 0; i <= 9; i++)
{
current = (struct node*)malloc(sizeof(struct node));
current-> data = i;
current-> next = tail;
tail = current;
current = current->next;
}
current = head;
while(current)
{
printf("i: %d\n", current-> data);
current = current->next;
}
}
建立列表時,您似乎被指針算法絆倒了。 嘗試以下方法:
int main(void)
{
struct node *head = NULL;
struct node *tail = NULL;
struct node *current;
int i;
for (i=0; i <= 9; i++)
{
struct node *temp = (struct node*)malloc(sizeof(struct node));
temp-> data = i;
temp-> next = NULL;
if (head == NULL) // empty list: assign the head
{
head = temp;
tail = temp;
current = head;
}
else // non-empty list: add new node
{
current-> next = temp;
tail = temp;
current = current->next;
}
}
// reset to head of list and print out all data
current = head;
while (current)
{
printf("i: %d\n", current-> data);
current = current->next;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.