列表,添加到最后,C编程代码

时间:2015-01-27 22:15:53

标签: c list compilation

我再次从我的讲座中得到一个代码,作为一个练习,我应该实现并运行。我正在使用Windows 8.1和Dev C ++,我刚刚开始使用C语言进行编程。编译器说我在第83和84行有两个错误:

root = insert_item_end(&root, 66);
root = insert_item_end(&root, 99);

但是当我运行它时它也会对第46行进行着色而我不知道为什么 - 编译器也没有告诉我什么。所以...如果你帮助我,我将非常感激:)

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct tnode{
    int value;
    struct tnode* next;
} node;


node *smem()
{
   node *pt;
   if((pt=(node *)malloc(sizeof(node)))==NULL){
      fprintf(stderr,"can not allocate memory\n");
      exit(1);
   }
};

//adding at the end, dodawanie na koniec
void insert_item_end(node **head,int val){
    node*temp =malloc(sizeof(node));
    if(!temp) return;
    temp ->value = val;
    temp ->next = NULL;
    if (*head) {
        node *tmp=*head;
        for(;tmp->next; temp= tmp->next);
        temp->next = temp;
    }
    else 
        *head=temp;
}

    //how to call this function, wywoałnie: insert_item_end(&head, val);

//creating a sorted list, tworzenie listy posortowanej
node *insert_item_sort(node* head, int key) {
    node *elem=malloc(sizeof(node));
    if(!elem)
        return head;
    elem -> value = key;
    elem -> next = NULL;
    if(head){
        if(head->value>key){        
            elem ->head = head;
            head = elem;
        }
        else{
            node *tp =head;
            for(;tp->next&&tp->next->value <key ; tp = tp->next);
            elem -> next =tp -> next;
            tp->next = elem;
        }
    }
    else 
        head=elem;
    return head;
}

node* print (node *lista)
{
    while(lista!=NULL)
    {
        printf("%d\n",lista->value);
        lista=lista->next;
    }
};

int main(void){
    node *p1,*p2,*p3,*root,*p;
    int n;
    p1=smem();
    p2=smem();
    p3=smem();

    root=p1; /* pocz±tek listy */
    p1->next=p2;
    p2->next=p3;
    p3->next=NULL;
    p=root;

    root = insert_item_end(&root, 66);
    root = insert_item_end(&root, 99); 
    root = insert_item_sort(root, 66);
    root = insert_item_sort(root, 999);
    print(root);
}

2 个答案:

答案 0 :(得分:2)

您的insert_item_end函数不返回任何内容(void),而在第83行和第84行,您将此函数的返回值(声明为无效)赋值给root。由于root被声明为node结构的指针,insert_item_end函数应返回指向结构的指针。 第46行也有错误,因为没有名为head的节点结构成员。

答案 1 :(得分:0)

第64行elem->next = head;头部不是节点的成员,因此您应该将insert_item_sort更正为:

if (head->value > key){        
    elem->next = head;
    head = elem;
}

并且 insert_item_end 会返回无效,因此您不能将其分配给 root ,这就是为什么第83行和第83行出现错误的原因84