我目前有一个if语句,在一个函数内执行,看起来像这样,但不编译,虽然我知道这是因为我在条件2和3之间执行的代码.
我要做的是创建一个函数,将一个新节点插入到正确位置的整数排序链表中.这样做,我需要测试三个条件.首先是列表是否为空.如果它是condition1满意的,一切都很好.第二个条件是列表中当前是否只有一个节点.如果是这种情况,则condition2满意并且一切都很好.
现在我们来解决问题.如果不满足前两个条件,则唯一的另一种可能性是列表包含至少两个节点.在这种情况下,需要初始化两个临时指针,一个指向Head一个,一个指向Head -> Next,以便跟踪列表中的当前位置,并便于将新节点插入列表中.
这些是使用放在condition2和之间的代码初始化的condition3.必须创建condition3它们因为它们依赖于它们,但是在它们之前创建它们condition1会导致分段错误.
任何人都可以告诉我如何实施这样的声明,或者甚至可能吗?我想保持代码尽可能简单,LinkedList :: Insert()我现在拥有的功能齐全的功能是一堆if语句,我在跟踪一些代码时遇到了麻烦.
int NewElement;
Node *NewNode;
NewNode = new Node;
NewNode -> Element = NewElement;
Node *TempPrevious;
Node *TempNext;
if (ListIsEmpty) // condition1
{
// some code
return true;
}
else if (ListContainsOnlyOneNode) // condition2
{
// some code
return false;
}
TempPrevious = Head;
TempNext = Head -> Next;
else if (NewNode -> Element > TempNext -> Element) // condition3
{
// some code
return true;
}
Run Code Online (Sandbox Code Playgroud)
这......真的很容易.因为你return来自每个区块,所以根本不需要else!
if (ListIsEmpty) // condition1
{
// some code
return true;
}
// you don't have anything that needs to happen here, but you *could*
// since if condition1 is met control leaves the function immediately
if (ListContainsOnlyOneNode) // condition2
{
// some code
return false;
}
// if either of the previous conditions are met,
// control will never reach this point! So put whatever setup you need for
// the final test here
TempPrevious = Head;
TempNext = Head -> Next;
if (NewNode -> Element > TempNext -> Element) // condition3
{
// some code
return true;
}
Run Code Online (Sandbox Code Playgroud)