我想創建一個從1到1000的數字鏈接列表並打印數字。 Im使用函數createList()
創建列表並printList()
來打印元素。 但是下面的代碼崩潰了。 任何人都可以糾正。我是新來的鏈表創建鏈接列表並打印元素?
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node* link;
};
struct node* head;
void deleteNode()
{
}
void createList()
{
int i;
struct node* temp = (struct node*)malloc(sizeof(struct node));
head = temp;
struct node* temp1 = (struct node*)malloc(sizeof(struct node));
for(i=0;i<10;i++)
{
temp->data = i+1;
temp->link = temp1;
temp1->link = temp++;
temp1++;
}
}
void printList()
{
struct node* temp = (struct node*)malloc(sizeof(struct node));
temp = head;
while(temp != NULL)
{
printf("%d ", temp->data);
temp = temp->link;
}
}
int main()
{
head = NULL;
createList();
printList();
return 0;
}
你在做什麼?只創建兩個元素並在其中放置10個元素? –
請參閱並更正您的創建方法.. http://www.c4learn.com/data-structure/c-program-to-create-singly-linked-list/ –
'但下面的代碼崩潰了 - 調試器可以告訴你究竟是哪一行代碼崩潰了,這是有人幫助你或幫助你自己的有用信息。你期待什麼'temp ++'和'temp1 ++'來完成? – Mike