所以我嘗試在C中創建一個帶有鏈表的多項式,到目前爲止我做得很好,但是我遇到了一個小問題,如果我試圖用exp 2插入5例如和6 exp 2它將打印5X2 + 6X2,我想我的輸出是11X2。有沒有一種方法我可以改變我的代碼來讓這種情況發生(我不知道這是可能的)在C中創建一個帶有鏈表的多項式
這裏是我的代碼:?
struct listNode
{
int coefficient;
int exponent;
struct listNode * nextPtr;
};
typedef struct listNode Node;
void insertNode(int cof,int exp, Node **start)
{
Node * node = (Node *)malloc(sizeof(Node));
if (node != NULL)
{
node->coefficient = cof;
node->exponent = exp;
node->nextPtr = NULL;
Node * previousNode = NULL, * currentNode = *start;
while (currentNode != NULL && currentNode->exponent > exp)
{
previousNode = currentNode;
currentNode = currentNode->nextPtr;
}
if (previousNode != NULL)
{
previousNode->nextPtr = node;
node->nextPtr = currentNode;
}
else
{
node->nextPtr = currentNode;
*start = node;
}
}
else
puts("No available memory! Node not inserted!");
}
void printPolynomial(char const *tag, struct Node *ptr)
{
Node * temp;
const char *pad = "";
temp = ptr;
printf("%s: ", tag);
while (temp != NULL)
{
if(temp->exponent==0){
printf("%s%d", pad, temp->coefficient);
temp = temp->nextPtr;
}
else{
printf("%s%dX%d", pad, temp->coefficient, temp->exponent);
temp = temp->nextPtr;
}
pad = " + ";
}
putchar('\n');
}
int main()
{
Node *p1=NULL;
Node **p2=&p1;
insertNode(3,5,p2);
insertNode(5,5,p2);
insertNode(8,0,p2);
printPolynomial("p1",p1);
return 0;
}
如果您發現已經有一個'X2'節點,只需添加係數,而不是插入重複節點? –
與你的問題無關,但是在'main'中,你可以簡單地寫'insertNode(...,...,'而不是使用'p2';後者只會增加混淆 –
...你應該得到在這裏擺脫了'struct':'void printPolynomial(char const * tag,struct Node * ptr)'來消除一些警告,這是正確的:void printPolynomial(char const * tag,Node * ptr)' –