开发者

Sorted Insert in linked list

Given a problem to insert a new node within a sorted linked list in the correct position, I have come up with the following solution.

void SortedInsert(node** headref, node* newnode) {
  node* prev = NULL;
  node* curr = *headref;
  for (; curr; ) {
    if (curr->info > newnode->info) {
      break;
    }
    prev = curr;
    curr = curr->next;
  }
  if (!prev) {
    newnode->next = *headref;
    *headref = newnode;
  } else {
    newnode->next = prev->next开发者_JAVA百科;
    prev->next = newnode;
  }
}

Does this work. Are there any edge cases this does not work for. Is there a simpler solution.


Instead of making curr point to the node before which you want to insert, make curr point to the pointer that points to the node before which you want to insert.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜