#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
typedef struct node node;
node* insertFront(node* head, int d);
node* insertBack(node* head, int d);
void print(node* head);
int max(node* head);
int min(node* head);
int locInList(node* head, int x);
int main()
{
node* head = NULL;
node* temp = NULL;
head = malloc(sizeof(node));
head = insertBack(head, 5);
head = insertFront(head, 4);
head = insertFront(head, 3);
head = insertBack(head, 6);
head = insertBack(head, 7);
print(head);
printf("\nMax: %d\n", max(head));
printf("Min: %d\n", min(head));
printf("locInList 5: %d\n", locInList(head, 5));
printf("locInList 9: %d\n", locInList(head, 9));
return 0;
}
node* insertFront(node* head, int d)
{
node *tmp = NULL;
tmp = malloc(sizeof(node));
tmp->data = d;
tmp->next = head;
head = tmp;
return head;
}
node* insertBack(node* head, int d)
{
node *ptr;
ptr->data=d;
ptr->next = NULL;
if(head==NULL)
{
head->data=d;
head->next=NULL;
}
else
{
node *temp=head;
while(temp->next != NULL)
{
temp=temp->next;
}
temp->next=ptr;
}
return head;
}
void print(node* head)
{
node *tmp = head;
while(tmp != NULL)
{
printf("%d ", tmp->data);
tmp = tmp->next;
}
}
int max (node* head)
{
int max;
while (head != NULL)
{
if (max > head->data)
max = head->data;
}
return max;
}
int min (node* head)
{
int min;
while (head != NULL)
{
if (min < head->data)
min = head->data;
}
return min;
}
int locInList(node* head, int x)
{
}
我在使用InsertBack函数时遇到麻烦,我想将d的值添加到head的末尾。
通过此代码获得的当前输出是:
3 4 0 7 7 7 7 7 7 7 ...重复
输出应该看起来像这样
34567最多:7最少:3
任何帮助将不胜感激。我对链表也很陌生。因此,任何帮助将不胜感激!
这里
您忘记为节点分配内存。