注册 登录
编程论坛 C语言论坛

C语言链表尾部插入新节点的问题

持剑的战士 发布于 2020-02-02 17:29, 2646 次点击
#include<stdio.h>
#include<stdlib.h>
#include<strings.h>
struct node
{
    int data;
    struct node *pnext;
};
struct node *create_node(int);
void insert_tail(struct node *,struct node *);
int main()
{
    struct node *pheader = create_node(0);
    insert_tail(pheader,create_node(1));
    insert_tail(pheader,create_node(2));
    insert_tail(pheader,create_node(3));
    printf("header node data = %d\n",pheader->data);
    printf("node 1 data = %d\n",pheader->pnext->data);
    printf("node 2 data = %d\n",pheader->pnext->pnext->data);
    printf("node 3 data = %d\n",pheader->pnext->pnext->pnext->data);
}
struct node *create_node(int data)
{
    struct node * p = (struct node*)malloc(sizeof(struct node));
    if(NULL == p)
    {
        printf("malloc error!\n");
        return NULL;
    }
    memset(p,0,sizeof(struct node));
    p->data = data;
    p->pnext = NULL;
    return p;
}
void insert_tail(struct node *ph,struct node *new)  [Error] expected ',' or '...' before 'new'
{
    int count = 0;
    while(NULL != ph)
    {
        ph = ph->pnext;
        count++;
    }
    ph->pnext = new;  [Error] expected type-specifier before ';' token
    ph->data = count + 1;
}
这是C语言链表尾部插入新节点的程序,但运行时总是出现2个错误,分别是上面两处红色部分,我改了好久也没有成功,希望大佬能给我提供点帮助。
4 回复
#2
wmf20142020-02-02 18:12
new是c++关键字,不能用作变量,另插入函数做如下修改,即可正常:
void insert_tail(struct node *ph, struct node *neww)
{
    int count = 0;
    while (NULL != ph->pnext)
    {
        ph = ph->pnext;
        count++;
    }
    ph->pnext = neww;  
        ph->data = count + 1;
}
#3
持剑的战士2020-02-02 20:47
回复 2楼 wmf2014
谢谢大佬解答,还帮我纠正了程序中的一个错误
#4
八画小子2020-02-03 00:24
编译器用错了。你再用C++编译器编译C程序。
#5
持剑的战士2020-02-03 19:54
回复 4楼 八画小子
谢谢大佬,我把后缀改下就好了
1