2014-09-22 81 views
0

我想排序一個多項式鏈表,其中度包含在節點中。例如,多項式5x^2 + 5x + 5的poly.term可以是2,1,0。不幸的是,我有一種方法添加了多項式,但是以相反的方式返回它們(5 + 5x + 5x^2),這不會讓我相信我要完成的這個任務,所以我需要爲它。我嘗試了幾次,但我似乎無法得到它的掛鉤 - 通過此方法傳遞鏈表的頭部僅返回我通過的頭並刪除剩餘的節點。有人可以幫我嗎?對這個鏈表進行排序?

另外,我可以使用addToRear方法,而添加多項式,而不是一個addToFront,但我似乎無法得到一個工作...我發佈我的進行中的排序方法和正在進行的addToRear下面,任何輸入將不勝感激!

private void sort(Node head)          // CURRENTLY BROKEN!!!!!!!!!! 
{ 
    Node temp; 
    Node curr = head; 
    while(curr.next != null) 
    { 
    if(curr.term.degree < curr.next.term.degree) //either degree is smaller or greater 
     {//swap 
      temp = curr; //save first element 
      curr = curr.next; //set first element to second 
      temp.next = curr.next; //set next of first to third 
      curr.next = temp; //set second element to the first that we saved before 
     } 
    curr = curr.next; //move to next element 
    } 
} 


private void addToBack(float coeff, int deg, Node head) 
{ 
    if(head==null) 
    { 
     // System.out.println("List empty, creating new node"); 
     Node n = new Node(coeff,deg,head); 
     head = n; 
     System.out.println(head.term.coeff); 
    } 
    else 
    { 
     Node n = new Node(coeff,deg,head); 
     Node temp = head; 
     while(temp.next!=null) 
     { 
      System.out.println("a"); 
      temp.next=temp; 
     } 
     head = n; 
    } 
} 
+0

您是否需要執行排序或只是反轉?後來更簡單。你也堅持你的鏈接列表的實現?你不能使用庫實現或簡單的數組嗎? – Aivean 2014-09-22 21:20:26

+0

逆轉是好的,雖然排序會更好,我認爲。不幸的是,這項任務僅限於鏈接列表,他們明確要求你與他們合作,並不會給他們轉換他們更容易的信用:(我已經花了幾個小時對此無濟於事 – hendersawn 2014-09-22 21:39:59

+0

是不是隻是'while( curr.next!= null)'應該只是'while(curr!= null)'? – 2014-09-22 21:45:40

回答

0

我會盡量指出你的一些錯誤。

  1. 您試圖做的排序(氣泡排序的一些修改)應該有兩個嵌套循環。外循環將爲while (changes),內循環迭代元素。當您交換兩個元素時,請製作changes = true

  2. 當交換元素不嘗試交換節點時,交換其值(term)。它是那麼容易,因爲那:

    Term temp = curr.term; curr.term = curr.next.term; curr.next.term = temp;

  3. 在addToBack你有兩個錯誤,第一,你似乎期望你給它分配(head = n;)後頭部將會改變的方法之外,但事實卻並非如此,您只更改本地副本。 其次,在else分支中,而不是head = n;應該有temp.next = n;

,而不是編寫單獨的方法addToBack你可以考慮建造列表的地方,這樣的:

head = elementSource.next(); 
tail = head; 
while (elementSource.hasNext()) { 
    tail.next = elementSource.next(); 
    tail = tail.next; 
} 

注意元素添加到列表的尾部。 這裏我用elementSource來代替你的實際元素來源,只是出於說明的原因。

0
if(curr.term.degree < curr.next.term.degree) //either degree is smaller or greater 
    {//swap problem should be here while swapping 
     node temp; 
     temp=curr; 
     curr=curr.next;//curr changes here 
     temp.next=curr; //maintaining the link 
    } 
curr = curr.next; //move to next element