2014-03-01 73 views
1

codepad linkenter image description here我試圖用雙指針插入到鏈表中,但我不明白我要去哪裏錯了我跟隨了堆棧溢出的其他鏈接,我甚至提到了幾本書,所以請幫助我.i保留代碼插入位置1.在輸出中,以前的插入丟失。如何使用雙指針插入單向鏈表?

struct node 
{ 
     int data; 
     node *next; 
}; 

void insert(node **head,int k,int pos)//k refers to the element to be inserted 
{ 
    if(pos==1) 
    { 
    node *newnode=(node *)malloc(sizeof(node)); 
    newnode->data=k; 
    newnode->next=*head; 
    *head=newnode; 
    } 
} 

    void print(node **head) 
    { 
    printf("the elements are.. "); 
    while(*head!=NULL) 
    { 
     printf("%d ",(*head)->data); 
    (*head)=(*head)->next; 
    } 
    printf("\n"); 
    } 
    int main() 
    { 
     insert(&head,5,1); 
     print(&head); 
     insert(&head,4,1); 
     print(&head); 
     return 0; 
    } 

對於可憐的縮進抱歉。我是初學者請幫助我。

+1

這不是有效的C代碼。請通過複製粘貼來發布您正在編譯和運行的* actual *代碼。此外,*告訴我們它不工作的方式*。 –

+0

也許這解釋了你在找什麼:http://www.macs.hw.ac.uk/~rjp/Coursewww/Cwww/linklist.html – theldoria

+0

爲什麼不把它裝入codepad.org或類似的? –

回答

1

您的打印功能不正確。你正在擦除你的頭(*head)=(*head)->next;。更改功能

void print(node **head) 
    { 
    printf("the elements are.. "); 
    node *temp = *head; 
    while(temp!=NULL) 
    { 
     printf("%d ",temp->data); 
    temp=temp->next; 
    } 
    printf("\n"); 
    } 

,您會收到以下輸出:

的元素。5
的元素。4 5

+0

你能解釋我爲什麼頭不去下一個位置 – saimadan

+0

它。但是新的價值被分配給頭部。所以當你打電話給'print'時(&head);'第二次你收到不正確的結果 – Avt

+0

所以我修改了實際的指針,非常感謝你找出錯誤 – saimadan

0

檢查了這一點。

struct node //Missed struct's name 
{ 
    int data; 
    node *next; 
}; 

void insert(node **head,int k,int pos)//k refers to the element to be inserted 
{ 
    if(pos==1) 
    { 
     node *newnode= new node(); 
     newnode->data=k; 
     newnode->next=*head; //You called head which is not a member of node's struct 
     *head=newnode; 
    } 
} 

int main() 
{ 
    node *head=NULL; 
    insert(&head,5,1); 
    insert(&head,4,1); 
} 
+0

*頭我傳遞的函數,並在C++中,我們可以省略結構字權?糾正我,如果我錯了 – saimadan

+0

不,我們不能。 & 在C++中你不能做到這一點: -Calling結構體的成員 「*頭」 沒有實例 -Unnamed結構: 結構{ .... } -Struct後面沒有用分號 - *頭=新聞,其中沒有定義任何地方新聞 你做得很好是什麼: -Passing指針列表的頭部,而不是頭本身: 你傳遞的節點**頭,而不是節點*頭。 –

+0

我想我們可以做一次檢查這個鏈接它的編譯http://鍵盤。org/NyUITHU3 – saimadan