#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int date;
struct node *next;
}Node;
int main()
{
//creat_linklist
Node *head = NULL, *current, *previous;
int n;
scanf("%d", &n);
while (n--)
{
current = (Node *)malloc(sizeof(Node *));
scanf("%d", ¤t->date);
current->next = NULL;
if (head==NULL)
head = current;
else
previous->next = current;
previous = current;
}
Node *temp;
Node *read;
temp = (Node *)malloc(sizeof(Node *));
scanf("%d", &temp->date); //insert_date
read = head;
while ((read->next->date)>=(temp->date))
read = read->next;
temp->next = read->next;
read->next = temp;
read = head;
while (read!=NULL)
{
printf("%d ", read->date);
read = read->next;
}
}
插入位置为什么不对
第19行 和 第31行错误,用mallo()申请了个结构体指针的空间,修改如下:
19行: current = (Node *)malloc(sizeof(Node));
31行: temp = (Node *)malloc(sizeof(Node));
为什么这样就对了
Node *temp;
Node *read;
int insert_date;
scanf("%d", &insert_date);
read = head;
while (read!=NULL) {
if (read->next->date>=insert_date) {
temp = (Node *)malloc(sizeof(Node *));
temp->date = insert_date;
temp->next = read->next;
read->next = temp;
break;
}
read = read->next;
}