我正在编写一个程序来乘以两个多项式。我需要一些建议,如何在polyProduct函数中的嵌套while循环中重新启动双链表。我的意思是,此时我需要回到列表的第一个位置。这是我到目前为止的代码:
#include "DLListInterface.h"
#include <stdio.h>
#include <stdlib.h>
int numRead(DLnode*,int);
void printList(DLnode*);
DLnode *polyProduct(DLnode*,DLnode*);
int main()
{
DLnode *number1;
DLnode *number2;
DLnode *result;
int readval;
int numbterms;
int i;
scanf("%d",&numbterms);
scanf("%d",&readval);
/* initial DLnode of number1*/
number1=(DLnode*)malloc(sizeof(DLnode));
number1->value=readval;
number1->next=NULL;
number1->prev=NULL;
readval=numRead(number1,numbterms);
scanf("%d",&numbterms);
scanf("%d",&readval);
number2=(DLnode*)malloc(sizeof(DLnode));
number2->value=readval;
number2->next=NULL;
number2->prev=NULL;
readval=numRead(number2,numbterms);
printf("\n");
printList(number1);
printList(number2);
result=polyProduct(number1,number2);
printList(result);
getch();
return 0;
}
int numRead(DLnode*number,int numbterms)
{
int readval,i;
DLnode *anothernode;
for(i=0;i<(numbterms*2)-1;i++)
{
scanf("%d",&readval);
anothernode=(DLnode*)malloc(sizeof(DLnode));
anothernode->value=readval;
anothernode->next=NULL;
anothernode->prev=Dlast(number);
Dlast(number)->next=anothernode;
}
return readval;
}
DLnode *polyProduct(DLnode*poly1,DLnode*poly2)
{
DLnode *result;
DLnode *newnode;
DLnode *first;
first=poly2;
newnode=(DLnode*)malloc(sizeof(DLnode));
newnode->value=(poly1->value)*(poly2->value);
newnode->next=NULL;
newnode->prev=NULL;
result=newnode;
poly1=poly1->next;
poly2=poly2->next;
newnode=(DLnode*)malloc(sizeof(DLnode));
newnode->value=poly1->value+poly2->value;
newnode->next=NULL;
newnode->prev=Dlast(result);
Dlast(result)->next=newnode;
poly1=poly1->prev;
poly2=poly2->next;
while(poly1!=NULL)
{
while(poly2!=NULL)
{
newnode=(DLnode*)malloc(sizeof(DLnode));
newnode->value=(poly1->value)*(poly2->value);
newnode->next=NULL;
newnode->prev=Dlast(result);
Dlast(result)->next=newnode;
poly1=poly1->next;
poly2=poly2->next;
newnode=(DLnode*)malloc(sizeof(DLnode));
newnode->value=poly1->value+poly2->value;
newnode->next=NULL;
newnode->prev=Dlast(result);
Dlast(result)->next=newnode;
poly1=poly1->prev;
poly2=poly2->next;
}
poly1=poly1->next;
poly2=first; //restart poly 2
}
return result;
}
void printList(DLnode*number)
{
while (number!=NULL)
{
printf("%d ",number->value);
number=number->next;
}
printf("\n");
return;
}
//Declaration of DLnode in DLList.h file
typedef struct Dcontainer
{
int value;
struct Dcontainer *next;
struct Dcontainer *prev;
} DLnode;
答案 0 :(得分:0)
进入列表开头的一种方法是操纵指针移动到列表的开头
void seekstart(DLNode* number)
{
while(number->prev != null)
{
number = number->prev;
}
}
另一个选项是使用临时节点在处理之前存储列表的Starting节点。
DLnode *temp_num1 = number1;
DLnode *temp_num2 = number2;
result=polyProduct(number1,number2);
或者您在节点本身的结构中保留指向根的指针。虽然这可能不是一个有效的解决方案。如果您需要经常访问列表的开头,这非常有用
// DLList.h文件中的DLnode声明
typedef struct Dcontainer
{
int value;
struct Dcontainer *next;
struct Dcontainer *prev;
struct Dcontainer *root; //root is the starting of the list
} DLnode;