LeetCode runtime error
阿新 • • 發佈:2019-01-03
今天在寫LeetCode的某一道題目時候,遇到runtime error問題,本地能過,submit後死活不能通過。
查了一下網上的一些答案,基本上都是陣列、指標沒有初始化造成野指標、陣列索引值越界。
看了自己的程式碼覺得沒啥問題,沒有到陣列,那隻能夠是連結串列的指標變成野指標的問題。仔細看了兩遍程式碼,終於發現是連結串列裡的random指標沒有初始化,在呼叫的時候很容易野。
Problem:
給定一個連結串列,每個節點包含一個額外增加的隨機指標,該指標可以指向連結串列中的任何節點或空節點。
要求返回這個連結串列的深度拷貝。
有問題的程式碼片段:
while(currentNode != NULL) { temp= (struct RandomListNode*)malloc(sizeof(struct RandomListNode)); temp->label = currentNode->label; temp->next = currentNode->next; currentNode->next = temp; currentNode = temp->next; }
加了初始化指標的程式碼:
while(currentNode != NULL) { temp= (struct RandomListNode*)malloc(sizeof(struct RandomListNode)); temp->label = currentNode->label; temp->next = currentNode->next; temp->random = NULL; //就是這裡出的問題,如果沒有初始化成NULL的話,指向的為止不知道是哪裡,伺服器會訪問出錯 currentNode->next = temp; currentNode= temp->next; }