程序设计作业的一个问题,有关链表和指针(已解决)
已给出主函数和fun.c,要设计函数
#include <stdio.h>
#include "fun.h"
int main(void) {
int n, num;
scanf("%d", &n);
struct Node* head = NULL;
while (n--) {
scanf("%d", &num);
insert(&head, num);
}
print_linklist(head);
delete_linklist(head);
}
#include <stdlib.h>
struct Node {
struct Node* next;
int value;
};
void insert(struct Node** head, int num);
void print_linklist(struct Node* head);
void delete_linklist(struct Node* head);
以下是我写的函数的设计
#include <stdlib.h>
#include <stdio.h>
#include "fun.h"
void insert(struct Node** head, int num)
{
struct Node *l;
struct Node *p;
l = *head;
if(l -> next == NULL) (在这里提示出了问题)
{
l -> next -> value = num;
}
else
{
if(num >= l -> value)
{
l = l -> next;
l -> value = num;
}
else
{
p = *head;
while(num > p -> next -> value)
{
p = p -> next;
}
struct Node *m;
struct Node *n;
n = p -> next;
m = p;
m -> next -> value = num;
m -> next -> next = n;
}
}
}
void print_linklist(struct Node* head)
{
while(head -> next != NULL)
{
printf("%d", head -> next -> value);
}
}
void delete_linklist(struct Node* head)
{
struct Node *l;
while(head -> next != NULL)
{
l = head -> next;
free(head);
head = l;
}
}
出了一些问题,搞了好久还是不知道为什么,请教一下各位大神!
你的打印函数
print_linklist
也有问题,你直接打印head-next
跳过了第一个节点,而且你没有在循环中让head
向下一个节点前进,如果前面的插入函数没问题,这个循环就会是无限循环,一直打印。