链接列表:如何在C中制作分拣机检查器?

时间:2017-09-04 23:59:01

标签: c data-structures linked-list nodes

我认为这应该正常工作......我不确定它有什么问题?这是我的代码片段。如果给定的整数列表不是按升序排列,则假设返回0,如果按升序排序,则返回1。

 struct Node{
    int data;
    Node *pNext;
 };

 int isItSorted(Node *pHead){
    while(pHead != NULL){
       if(pHead->data > pHead->pNext->data) 
          return 0;
       else
          return 1;
       pHead = pHead->pNext;
    }
    return 1;
 }

3 个答案:

答案 0 :(得分:1)

当你在没有先检查pHead->pNext->data的情况下pHead->pNext != NULL时,你会调用未定义的行为,正如@Dai所说。另外,正如@JohnBollinger所说,return 1内部有一个while ,所以它会在检查list[0] < list[1]后返回,而不是通过整个事情。< / p>

struct Node{
    int data;
    Node *pNext;
};

int isItSorted(Node *pHead){
   while(pHead != NULL && pHead->pNext != NULL) { // 0 and 1 element lists are always sorted, so this is fine.
      if(pHead->data > pHead->pNext->data) 
          return 0; // Break out and return
      else
          pHead = pHead->pNext; // Or keep going
   }
   return 1; // Lift out end case from loop
}

这里也是一个尾递归版本:(编辑:clanggcc似乎都不够聪明,即使使用-O3也会发现尾递归。哦,好吧。)

int isSorted(Node *list) {
  return list == NULL // [] is sorted
      || list->pNext == NULL // [x] is sorted
      || list->data <= list->pNext->data && isSorted(list->pNext); // x:y:z is sorted if x < y and y:z is sorted
}

答案 1 :(得分:0)

这是你的(主要)问题:

if(pHead->data > pHead->pNext->data) 
   return 0;
else
   return 1;

在循环中执行此操作将立即返回一个或零仅基于前两个项目的比较。假设你至少有两个项目,否则你有未定义的行为,因为你取消引用空指针。

我会按如下方式实现它(伪代码),前面是普通检查以捕获边缘情况(少于两个项目),继续检查项目是否有序而不是返回一张支票:

def isSorted(head):
    # Less than two items means sorted no matter what the data is.

    if head == NULL:
        return true

    if head.next == NULL:
        return true

    # Continue while there are at least two items to check.

    node = head
    while node.next != NULL:
        # If those two items out of order, it'snot sorted.
        # If they are in order, advance and keep checking.

        if node.data > node.next.data:
            return false
        node = node.next

    # Reaching here means all items were in order.

    return true

答案 2 :(得分:0)

代码中只有一个错误:

struct Node{
    int data;
    Node *pNext;
 };

 int isItSorted(Node *pHead){
    while(pHead != NULL){
       if(pHead->next != NULL && pHead->data > pHead->pNext->data) {
          return 0;
       }
       pHead = pHead->pNext;
    }
    return 1;
 }

每当处理循环时,请务必检查退出条件。 例如,在你的代码中,如果它没有进入IF块,那么它必然会返回1.并且你的循环迭代永远不会重复。

所以这就是全部。确保在处理循环时考虑EXIT条件。