我的目标是创建一个函数来减去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
答案 0 :(得分:0)
在
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
s,同时还有很多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
}
}