2011-03-18 28 views
2

我目前有一个if语句,从一个函数内部执行,看起来像这样,但不能编译,尽管我知道这是因为我的代码在条件2和3之间执行。在'if'语句的条件之间放置代码

我想要做的是创建一个函数,该函数将一个新节点插入正确位置的已排序整数链表中。做这个,我需要测试三个条件。首先是列表是否为空。如果是,那么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; 
    } 

回答

6

这是......其实很简单。因为你是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; 
} 
4

删除最后else,我认为它会随你喜欢。