[英]Sorting this linked lists?
我正在嘗試對節點中包含度的多項式鏈接列表進行排序。 例如,多項式5x ^ 2 + 5x + 5的多項式度為2,1,0。 不幸的是,我有一個添加多項式但以相反的方式(5 + 5x + 5x ^ 2)返回多項式的方法,這對我要完成的作業沒有讓我功勞,因此我需要為它。 我嘗試了幾次,但似乎無法理解它-通過此方法傳遞鏈表的頭僅返回我經過的頭,並刪除其余節點。 有人可以幫我嗎?
或者,我可以在添加多項式而不是addToFront的同時使用addToRear方法,但是我似乎無法正常工作...我在下面同時發布了正在進行的排序方法和正在進行的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;
}
}
我會嘗試指出一些錯誤。
您嘗試執行的排序(對冒泡排序的某些修改)應該具有兩個嵌套循環。 外循環將是while (changes)
,內循環將迭代元素。 交換兩個元素時,請進行changes = true
。
當交換元素不嘗試交換節點時,請交換其值( term
)。 就這么簡單:
Term temp = curr.term; curr.term = curr.next.term; curr.next.term = temp;
在addToBack中,您有兩個錯誤,首先,您似乎期望head在分配方法后會在方法之外更改( 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
代替了您實際的元素來源。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.