我剛剛學習了 C 中鏈表的概念,并嘗試實作它。我所做的是創建一個指標head和一個指標itr。要創建一個新節點,我將正常初始化一個節點(不使用指標),然后將指標附加到它。
struct node temp; //A single node contains a value 'num' and a pointer to the next node.
temp.num=x;
temp.next=NULL;
if(head==NULL){
head=&temp;
}
else{
itr=head;
while(itr->next!=NULL){
itr=itr->next;
}
itr->next=&temp;
}
這種方法不起作用,并且基于我對 C 中指標的有限了解,我無法弄清楚原因。我知道正確的方法是使用 malloc 創建新節點,但我需要知道為什么這種方法不起作用。
完整程式:
#include <stdio.h>
struct node{
int num;
struct node *next;
};
int main(){
struct node *head=NULL;
struct node *itr;
struct node temp;
int choice;
printf("1. Enter new Node, 2. Traverse all nodes, 3. Exit.");
int x;
while(1){
printf("\nEnter your choice: ");
scanf("%d", &choice);
if(choice==1){
printf("Enter value: ");
scanf("%d", &x);
temp.num=x;
temp.next=NULL;
if(head==NULL){
head=&temp;
}
else{
itr=head;
while(itr->next!=NULL){
itr=itr->next;
}
itr->next=&temp;
}
}
else if(choice==2){
if(head==NULL){
printf("Empty List");
continue;
}
printf("The values are: ");
itr=head;
printf("%d ", itr->num);
while(itr->next!=NULL){
itr=itr->next;
printf("%d ", itr->num);
}
}
else{
break;
}
}
}
uj5u.com熱心網友回復:
一個鏈表一般由若干個節點組成,其中每個節點指向鏈表中的下一個節點。鏈表中的最后一個節點應該指向NULL以標記鏈表的結尾。
但是,您只為單個節點分配了記憶體。因此,您將只能在鏈表中存盤單個節點。
將第一個節點添加到鏈表的代碼是正確的。但是,添加第二個節點的代碼無法作業,因為您沒有為第二個節點分配任何記憶體。
添加第二個節點的代碼實際上是在覆寫第一個節點,并使第一個節點指向自身。這就是為什么你會得到一個無限回圈,如果你之后嘗試列印鏈接串列。
因此,我建議您改為使用malloc為節點分配記憶體。這樣,您將不會被限制在單個節點上。
uj5u.com熱心網友回復:
你必須展示你的整個代碼。我想,在你的情況下,如果你定義一個這樣的函式,tempelem 是函式區域變數,你需要使用 malloc 使它可以從函式中訪問。
int addNode(struct node *head, inx x) {
struct node temp; //A single node contains a value 'num' and a pointer to the next node.
temp.num=x;
temp.next=NULL;
if(head==NULL){
head=&temp;
}
else{
itr=head;
while(itr->next!=NULL){
itr=itr->next;
}
itr->next=&temp;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/406174.html
標籤:
上一篇:C中的串列和指標
下一篇:結構指標及其初始化
