c语言 链表的数据插入,在链表中插入数据!求助!!!

该楼层疑似违规已被系统折叠 隐藏此楼查看此楼

include

#include

struct student

{

int data;

struct student *next;

};

void main()

{

int n=0;

struct student *head,*p1,*p2,*p,*q;

p1=p2=(struct student *) malloc (sizeof(struct student));

scanf("%d",&p1->data);

head=NULL;

while(p1->data!=0)

{

n=n+1;

if(n==1)

head=p1;

else

p2->next=p1;

p2=p1;

p1=(struct student *) malloc (sizeof(struct student));

scanf("%d",&p1->data);

}

p2->next=NULL;

printf("input the number to insert:\n");

p=(struct student *) malloc (sizeof(struct student));

scanf("%d",p->data);

p1=head;

while((p->data>p1->data)&&(p1->next!=NULL))

{

q=p1;

p1=p1->next;

}

if(p->data<=p1->data)

{

q->next=p;

p->next=p1;

}

n=n+1;

p=head;

while(p!=NULL)

{

printf("%d",p->data);

p=p->next;

}

}

输入一组数据,然后输入一个数插入到原链表,不用考虑大于第一个节点和小于最后一个节点的情况,我现在只要实现这个功能。不管我输入什么数,都只会按原样输出,如先输入1,3,5。输入2插入,可是输出是1,3,5。高手看看那错了

好的,我会尽力回答你的问题。以下是实现线性链表插入的 C 语言代码: ```c #include <stdio.h> #include <stdlib.h> // 定义链表节点结构体 struct Node { int data; struct Node* next; }; // 定义链表头指针 struct Node* head = NULL; // 在链表尾部插入新节点 void insert(int value) { // 创建新节点 struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); new_node->data = value; new_node->next = NULL; // 如果链表为空,则新节点为头节点 if (head == NULL) { head = new_node; return; } // 遍历链表,找到尾节点 struct Node* current = head; while (current->next != NULL) { current = current->next; } // 将新节点插入到尾节点后面 current->next = new_node; } int main() { int n, i, value; printf("请输入要插入的节点个数:"); scanf("%d", &n); for (i = 1; i <= n; i++) { printf("请输入节点 %d 的值:", i); scanf("%d", &value); insert(value); } // 遍历链表,输出所有节点的值 printf("链表的节点值为:"); struct Node* current = head; while (current != NULL) { printf("%d ", current->data); current = current->next; } printf("\n"); return 0; } ``` 以上代码实现了在链表尾部插入节点的功能。在运行程序时,会先提示用户输入要插入的节点个数,然后依次要求用户输入每个节点的值。最后,程序会输出链表所有节点的值。 注意,在实际开发,还需要考虑链表已有节点的情况,比如插入节点时需要保证链表节点的顺序不变。此外,还需要考虑内存管理等问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值