2014-01-08 77 views
0

我想創建一個從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; 
} 
+0

你在做什麼?只創建兩個元素並在其中放置10個元素? –

+0

請參閱並更正您的創建方法.. http://www.c4learn.com/data-structure/c-program-to-create-singly-linked-list/ –

+0

'但下面的代碼崩潰了 - 調試器可以告訴你究竟是哪一行代碼崩潰了,這是有人幫助你或幫助你自己的有用信息。你期待什麼'temp ++'和'temp1 ++'來完成? – Mike

回答

3
void createList(){ 
    int i, size = 10; 
    struct node* temp = malloc(sizeof(struct node)); 
    head = temp; 

    for(i=0;i<size;i++){ 
     temp->data = i+1; 
     temp->link = i < size - 1 ? malloc(sizeof(struct node)) : NULL; 
     temp = temp->link; 
    } 
} 

void createList(){ 
    int i, size = 10; 
    struct node* temp = malloc(size*sizeof(struct node)); 
    head = temp; 

    if(temp){ 
     for(i=0;i<size;i++){ 
      temp->data = i+1; 
      temp->link = temp + 1; 
      ++temp; 
     } 
     temp[-1].link = NULL; 
    } 
} 
0
void createList() 
{ 
    int i; 
    struct node *temp, *loc_head; 
    loc_head = head; 

    for(i=0;i<10;i++) 
    { 
     struct node* newnode = malloc(sizeof(struct node)); 
     newnode->data = i+1; 
     newnode->link = NULL; 
     if(head == NULL) { 
      head=newnode; 
      loc_head = newnode; 
     } 
     else { 
      head->link = newnode; 
      head = newnode; 
     } 
    } 
    head = loc_head; 
} 

don't typecast the result of malloc

-1

鑑於元素的數組,創建數組鏈表(每 一個新節點元素,使用將節點添加到列表末尾的函數)。

+0

那麼,有什麼問題嗎?沒有人在做你的任務,如果你不先做出努力的話。 – Warlord