【问题标题】:Placing code in between conditions of an 'if' statement在“if”语句的条件之间放置代码
【发布时间】:2011-03-18 17:39:36
【问题描述】:

我目前有一个 if 语句,从一个函数中执行,看起来像这样,但它不能编译,虽然我知道这是因为我在条件 2 和 3 之间执行的代码。

我要做的是创建一个函数,它将一个新节点插入到正确位置的整数排序链表中。这样做,我需要测试三个条件。首先是列表是否为空。如果是,那么condition1 很满意,一切都很好。第二个条件是当前列表中是否只有一个节点。如果是这样,那么condition2 就很满意了,一切都很好。

现在我们来解决问题。如果前两个条件不满足,那么唯一的另一种可能性是列表包含至少两个节点。在这种情况下,需要初始化两个临时指针,一个指向Head,一个指向Head -> Next,以便跟踪当前在列表中的位置,方便将新节点插入到列表中。

这些使用位于condition2condition3 之间的代码进行初始化。这些必须创建,因为 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;
    }

【问题讨论】:

    标签: c++ linked-list logic


    【解决方案1】:

    这……其实真的很简单。因为您在每个区块中都是 returning,所以您根本不需要 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;
    }
    

    【讨论】:

      【解决方案2】:

      删除最后一个else,我认为它会如你所愿。

      【讨论】:

        猜你喜欢
        • 2011-04-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-17
        相关资源
        最近更新 更多