开发者

Placing code in between conditions of an 'if' statement

I currently have an if statement, executing from within a function, that looks like this, but which doesn't compile, although I know it's because of the code I'm executing in between conditions 2 and 3.

What I'm trying to do is create a function that will inserted a new node into a sorted linked list of integers at the correct position. Do do this, I need to test for three conditions. The first is whether or not the list is empty. If it is then condition1 is satisfied and all is good. The second condition is whether or not there is only a single node currently in the l开发者_如何学Goist. If this is the case, then condition2 is satisfied and again all is good.

Now we come to the problem. If the first two conditions are not satisfied, then the only other possibility is that the list contains at least two nodes. In this case, the two temporary pointers need to be initialised, one pointing to Head and one to Head -> Next in order to keep track of the current position in the list and facilitate the insertion of the new node into the list.

These are initialised using the code the is placed between condition2 and condition3. These have to be created because condition3 relies on them, but creating them before the condition1 would result in a segmentation fault.

Can anyone advise me on how to go about implementing such a statement, or if it's even possible? I want to keep the code as simple as possible, and the fully functioning LinkedList :: Insert() function I have right now is a mess of if statements and I'm having trouble following some of the code.

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;
    }


This is... actually really easy. Because you're returning from each block, you don't need else at all!

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;
}


Remove the last else and I think it will work as you like.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜