【发布时间】:2010-09-12 18:22:32
【问题描述】:
我几乎完成了这项任务,这让我很生气。这是我关于这三个不同部分的第三篇文章,老实说,我很尴尬,因为我正在为这项任务而苦苦挣扎。
任务本身是编写一个程序,使用链表执行大整数的加法和减法(我慢慢开始讨厌链表,在 Lisp 之外)。现在一切似乎都在工作,除了实际的加法和减法。我不确定它是否是算术函数,因为它们以前可以工作(但从来没有 100%),但与 S/O 社区核实并没有什么坏处(通常我不会要求这么多帮助完成一项任务,因为我更喜欢自己解决问题,但这是糟糕而忙碌的一周,而且截止日期快到了)。
我写的算术函数如下,谁能帮我找出问题所在?
/*
* Function add
*
* @Paramater STRUCT* Integer
* @Parameter STRUCT* Integer
*
* Takes two linked lists representing
* big integers stored in reversed order,
* and returns a linked list containing
* the sum of the two integers.
*
* @Return STRUCT* Integer
*
* TODO Comment me
*/
struct integer* add( struct integer *p, struct integer *q )
{
int carry = 0;
struct integer *sHead, *sCurr;
struct integer *pHead, *qHead;
pHead = p;
qHead = q;
sHead = NULL;
while( p )
{
sCurr = ( struct integer* ) malloc (sizeof(struct integer));
sCurr->digit = p->digit + q->digit + carry;
sCurr->next = sHead;
sHead = sCurr;
carry = 0;
/*
* If the current digits sum to greater than 9,
* create a carry value and replace the current
* value with value mod 10.
*/
if( sCurr->digit > 9 )
{
carry = 1;
sCurr->digit = sCurr->digit % 10;
}
/*
* If the most significant digits of the numbers
* sum to 10 or greater, create an extra node
* at the end of the sum list and assign it the
* value of 1.
*/
if( carry == 1 && sCurr->next == NULL )
{
struct integer *sCarry = ( struct integer* ) malloc (sizeof(struct integer));
sCarry->digit = 1;
sCarry->next = NULL;
reverse( &sCurr );
sCurr->next = sCarry;
reverse( &sCurr );
}
p = p->next;
if( q->next ) q = q->next;
else q->digit = 0;
}
return sHead;
}
/*
* Function subtract
*
* @Parameter STRUCT* Integer
* @Parameter STRUCT* Integer
*
* Takes two linked lists representing struct integers.
* Traverses through the lists, subtracting each
* digits from the subsequent nodes to form a new
* struct integer, and then returns the newly formed
* linked list.
*
* @Return STRUCT* Integer
*
* TODO Comment me
*/
struct integer* subtract( struct integer *p, struct integer *q )
{
int borrow = 0;
struct integer *dHead, *dCurr;
struct integer *pHead, *qHead;
pHead = p;
qHead = q;
dHead = NULL;
while( p )
{
dCurr = (struct integer*) malloc (sizeof(struct integer));
if( q )
{
dCurr->digit = p->digit - q->digit - borrow;
}
else
{
dCurr->digit = p->digit - borrow;
}
dCurr->next = dHead;
if( dCurr->digit < 0 )
{
dCurr->digit += 10;
borrow = 1;
}
dHead = dCurr;
p = p->next;
if( q->next) q = q->next;
}
return dHead;
}
示例输出应如下所示:
8888888888 + 2222222222 = 11111111110
10000000000 – 9999999999 = 1
10000000000 – 9999999999 = 1
但是,它看起来像这样:
8888888888 + 2222222222 = 1111111110
10000000000 - 9999999999 = 10000000001
10000000000 - 9999999999 = 10000000001
编辑整个程序(截至美国东部标准时间下午 3:30 的当前形式)可通过here 参考,或者在这些功能不是问题的情况下提供。
【问题讨论】:
-
如何使用调试器并显示每个步骤发生了什么。似乎这不是关于链表本身,而是关于你如何减去。顺便说一句,最好在减法中将其命名为“借”而不是“进位”。
-
特别感兴趣的是 dCurr->digit、p->digit、q->digit 的输出。而且您还没有显示整数类型是如何定义的。
-
@Pmod 对不起,我会把整个程序的粘贴箱作为参考。
标签: c linked-list