一个关于malloc函数位置问题
第一个方式一运行就崩溃 搞得我崩溃
第二个是我玄学操作搞对了
能有大神给帮我解答一下么跪求了
这是pta
6-2 删除单链表偶数节点 (15分)题目
struct ListNode *createlist()
{
struct ListNode *head,*p,*q;int m;
head=NULL;
p=q=(struct ListNode *)malloc(sizeof(struct ListNode *));
while(scanf("%d",&m)&&m!=-1)
{
p->data=m;
if(head==NULL)head=p;
else q->next=p;
q=p;
p=(struct ListNode *)malloc(sizeof(struct ListNode *));
}
p=NULL;
return head;
}
struct ListNode *createlist()
{
struct ListNode *head,*p,*q;int m,oo;
head=NULL;
while(scanf("%d",&m)&&m!=-1)
{
p=(struct ListNode *)malloc(sizeof(struct ListNode *));
p->data=m;
if(head==NULL)head=p;
else q->next=p;
q=p;
}
p->next=NULL;
return head;
}
完整的代码
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int data;
struct ListNode *next;
};
struct ListNode *createlist();
struct ListNode *deleteeven( struct ListNode *head );
void printlist( struct ListNode *head )
{
struct ListNode *p = head;
while (p) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main()
{
struct ListNode *head;
head = createlist();
head = deleteeven(head);
printlist(head);
return 0;
}
typedef struct ListNode *List;
struct ListNode *createlist()
{
struct ListNode *head,*p,*q;int m;
head=NULL;
p=q=(struct ListNode *)malloc(sizeof(struct ListNode *));
while(scanf("%d",&m)&&m!=-1)
{
p->data=m;
if(head==NULL)head=p;
else q->next=p;
q=p;
p=(struct ListNode *)malloc(sizeof(struct ListNode *));
}
p=NULL;
return head;
}
struct ListNode *deleteeven( struct ListNode *head )
{
struct ListNode *p,*q;
p=head;
while(head && head->data%2==0){
p = head;
head = head->next;
free(p);
}
p=head;
while(p&&p->next)
{
while(p->next&&p->next->data%2==0)
{
q=p->next;
p->next=q->next;
}
p=p->next;
}
return head;
}