有好多问题#include <stdio.h>
#include <malloc.h>
#include <math.h>
#define LEN sizeof(struct ListNode)
struct ListNode
{
int val;
struct ListNode *next;
};
int n;
struct ListNode*creat()
{
struct ListNode*head;
struct ListNode*p1,*p2;
n=0;
p1=p2=(struct ListNode*)malloc(LEN);
scanf("%d",&p1->val);
head=NULL;
while(p1->val!=-1)
{
n=n+1;
if(n==1)head=p1;
else p2->next=p1;
p2=p1;
p1=(struct ListNode*)malloc(LEN);
scanf("%d",&p1->val);
}
p2->next=NULL;
return(head);
}
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2)
{
int num1=0,num2=0,num=0;
//int count=0,s=0,t;
int count=0;
struct ListNode*p,*q;
p=NULL;
q=p;
//while(l1->val!=-1)
while(l1)
{
//num1=num1+(l1->val)*(10^count);
num1 = num1 + l1->val * pow(10, count);
l1=l1->next;
count++;
}
count=0;
//while(l2->val!=-1)
while(l2)
{
/*num2=num2+(l2->val)*(10^count);*/
num2 = num2 + l2->val * pow(10, count);
l2=l2->next;
count++;
}
struct ListNode *head = NULL;
p = q = NULL;
num = num1 + num2;
do {
p = malloc(sizeof(struct ListNode));
p->next = NULL;
p->val = num % 10;
num /= 10;
if(!head) head = q = p;
else q->next = p, q = q->next;
} while(num);
return head;
/*
count=0;
num=num1+num2;
t=num;
if(num==0)
{
// 不申请内存?
p->val=0;
p->next=NULL;
}
else
{
while(t)
{
t=t/10;
s++;
}
p->val=num/(10^count)%10;
count++;
for(int i=2;i<=t;i++)
{
p=p->next;
p->val=num/(10^count)%10;
count++;
}
p->next=NULL;
}
return q;
*/
}
void print(struct ListNode*head)
{
struct ListNode*p;
p=head;
if(head!=NULL)
do
{
printf("%d ",p->val);
p=p->next;
}while(p!=NULL);
}
int main()
{
struct ListNode *l1,*l2,*head;
l1=creat();
l2=creat();
head=addTwoNumbers(l1,l2);
print(head);
// 又不释放内存
return 0;
}
|