2016-10-28 63 views
0

所以我嘗試在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; 
} 
+1

如果您發現已經有一個'X2'節點,只需添加係數,而不是插入重複節點? –

+0

與你的問題無關,但是在'main'中,你可以簡單地寫'insertNode(...,...,​​'而不是使用'p2';後者只會增加混淆 –

+0

...你應該得到在這裏擺脫了'struct':'void printPolynomial(char const * tag,struct Node * ptr)'來消除一些警告,這是正確的:void printPolynomial(char const * tag,Node * ptr)' –

回答

0

插入功能是錯誤的。插入期間,您只需要存儲coefficientexponent。否則使用標準方法添加節點。本變形例後

void insertNode(int cof, int exp, Node **start) 
{ 
    Node *node = malloc(sizeof(Node)); 
    if (node != NULL) 
    { 
     node->coefficient = cof; 
     node->exponent = exp; 
     node->nextPtr = NULL; 

     if (*start != NULL) 
     { 
      Node *walk = *start; 
      Node *tail = NULL; 
      while (walk) 
      { 
       tail = walk; 
       walk = walk->nextPtr; 
      } 
      tail->nextPtr = node; 
     } 
     else 
     { 
      *start = node; 
     } 
    } 
    else 
     puts("No available memory! Node not inserted!"); 
} 

輸出:

P1:3X5 + 5X5 + 8

而且不需要鑄造在Node *node = (Node*)malloc(sizeof(Node));除非這是C++程序,在這種情況無論如何你不應該使用malloc。一般情況下,避免在編譯器沒有要求並且沒有抱怨時使用強制轉換。

0
if (previousNode != NULL) 
{ 
    if (previousNode->exponent == exp) 
    { 
     previousNode->coefficient += coef; 
     // Keep in mind you have allocated memory for node that you do not need 
    } 
    else 
    { 
     previousNode->nextPtr = node; 
     node->nextPtr = currentNode; 
    } 
} 
+0

不只是提供一些代碼,你可以解釋你的答案? –

相關問題