2017-09-09 61 views
0
typedef struct node{ 
int data; 
struct node *link; 
}nd; 

nd *head=NULL , *ahead=NULL; 

void create_node(int item) { 
    nd *new, *temp; 
    new = (nd*)malloc(sizeof(nd)); 
    new->data=item; 
    new->link=NULL; 
    if(head==NULL) { 
     head=new; 
    } 
    else { 
     temp=head; 
     while(temp->link!=NULL) { 
      temp=temp->link; 
     } 
     temp->link=new; 
    } 

} 

void alpha_check(int size) { 
    int i,j,num; 
    nd *ti , *tj; 
    ti=tj=head; 
    for(i=1 ; i<=size ; i++) { 
     for(j=1 ; j<=size ; j++) { 
      num = ((ti->data)*10)+(tj->data); 
      tj=tj->link; 

      /*if(num>=65 && num<=90) { 
        printf("\n->%d",num); 
       }*/ 
     } 
    //ti=ti->link; 
    } 
} 

void traverse(nd *thead) { 
    while(thead->link!=NULL) { 
     printf("%d ",thead->data); 
     thead=thead->link; 
    } 
    printf("%d ",thead->data); 
} 

所以在上面的代碼唯一的問題在於功能alpha_check我想要的變量TJ點到下一個節點()。而不是指向下一個節點,它給了我分段錯誤(核心轉儲)。 請解釋爲什麼我不能讓tj指向下一個節點。鏈接列表分段故障

+0

爲(I = 1; I <=大小;我++){ 爲 (J = 1;Ĵ<=大小; J ++){ 。是一個問題..你需要添加一個標誌來遍歷,直到thread-> link!= NULL –

+0

我們看不到如何創建列表,也不知道如何調用'alpha_check'。看起來這個「大小」是錯誤的。使用大小而不是while循環遍歷列表直到列表結束也很奇怪。使用調試器。它會告訴你什麼是錯的,它發生在哪裏。 –

+0

你傳遞給函數alpha_check的大小是多少? – Ganeshdip

回答

1

分段錯誤是內核發出的一個信號,表示程序正在訪問內存,它沒有權限導致內核終止程序。這通常意味着你超出了數組的界限,或者在你的情況下,你正在引用一個指向它不應該是的東西的指針。像其他人暗示的其他人一樣,遍歷鏈表時需要使用不同類型的約束,而不是遍歷數組時的約束。在檢查節點指針不是NULL而不是在for循環中做一些固定大小的時候,你需要遍歷它。

我對您的alpha_check過程進行了更改,並添加了一個用於測試它的主體。它可以像你期望的那樣工作。

#include <stdio.h> 
#include <stdlib.h> 

typedef struct node { 
    int data; 
    struct node* link; 
} nd; 

nd *head=NULL , *ahead=NULL; 

void create_node(int item) { 
    nd* new,* temp; 
    new = (nd*)malloc(sizeof(nd)); 
    new->data = item; 
    new->link = NULL; 

    printf("%d %p\n", new->data, new); 

    if(head == NULL) { 
     head = new; 
    } 
    else { 
     temp = head; 
     while(temp->link) 
      temp = temp->link; 
     temp->link = new; 

    } 
} 

void alpha_check(int size) { 
    int i,j,num; 
    nd* ti ,* tj; 
    ti = tj = head; 

    for(i = 1 ; i <= size ; i++) { 
     while(tj) { 
      num = ti->data * 10 + tj->data; 
      tj = tj->link; 

     //if(num>=65 && num<=90) 
     //{ 
      printf("\n->%d",num); 
      printf(" %p\n", tj); 
     //} 
    } 
    //ti=ti->link; 
    } 
} 

void traverse(nd* thead) { 
    while(thead->link) { 
     printf("%d ", thead->data); 
     thead = thead->link; 
    } 
    printf("%d ", thead->data); 
} 

int main(void) { 
    create_node(10); 
    create_node(1); 
    create_node(5); 

    alpha_check(2); 
    return 0; 
} 
+0

如果您創建一個包含頭指針和一些跟蹤列表大小的變量的結構,則可以使用for循環的大小。 'struct List { size_t size; nd * head; nd * head; }' 您也可以使用for循環代替while循環來檢查指針是否爲空'for(tj = head; tj; tj = tj-> link)' –

+0

感謝您的幫助。有用。 –