[英]segmentation fault while subtracting 2 consecutive nodes of a linked list
我的目標是創建一個函數來減去 2 個連續的數字,然后將該結果添加到這些數字的前面
例如:
輸入:2->4->1->6->9->8->7
輸出:-2->2->4->-5->1->6->1->9->8->7
所以這是我到目前為止的邏輯:
struct node
{
int data;
node *next;
};
void SubtractConsecutiveNodes()
{
if(head==NULL || head->next==NULL)
{
return;
}
node *first =head,*prev;
node *newNode;
while(first!=NULL&&first->next!=NULL)
{
newNode->data=first->data-first->next->data;
newNode->next = first;
if(head== first)
head = newNode;
else
prev->next=newNode;
prev = first->next;
first=first->next->next;
}
}
但問題是在執行第一次迭代循環后似乎進入分段錯誤然后崩潰。
鏈接到我的整個代碼: Assignment-3
在
void SubtractConsecutiveNodes()
{
if(head==NULL || head->next==NULL)
{
return;
}
node *first =head,*prev;
node *newNode;
while(first!=NULL&&first->next!=NULL)
{
newNode->data=first->data-first->next->data;
newNode->next = first;
if(head== first)
head = newNode;
else
prev->next=newNode;
prev = first->next;
first=first->next->next;
}
}
newnode
在它被取消引用之前沒有指向任何東西
newNode->data=first->data-first->next->data;
崩潰是使用未初始化的指針可能導致的更禮貌的事情之一,因此
node *newNode = new node;
一切順利。
我恨prev
變量。 我不知道為什么。 也許我前世被謀殺之類的。 無論如何,有一個指向指針的巧妙技巧,您可以使用它來擺脫prev
,同時擺脫許多特定於head
邏輯。
很多時候多重間接(指向指針的指針)是不受歡迎的,但指針就像火:一個強大的仆人,但一個可怕的主人。 掌握指針並通過Crom,您可以編寫一些很酷的軟件!
void SubtractConsecutiveNodes()
{
// if first is a pointer to a pointer to a node, we can point it at a `next`
// and eliminate the need for prev. This has the added bonus of turning head
// into just another next pointer, eliminating all of the head-specific logic.
// if(head==NULL || head->next==NULL) is identical to the while exit condition
// once head is hidden behind first. Chuck it. You don't need it.
node **first = &head;
while ((*first) != NULL && (*first)->next != NULL)
// extra level of indirection, so extra dereferencing required.
{
node *newNode = new node;
newNode->data = (*first)->data - (*first)->next->data;
newNode->next = *first;
(*first) = newNode; // places newnode directly into prev->next or head,
// whichever happens to be there.
first = &(*first)->next->next->next;
//since we added another node in we need an extra ->next
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.