合并链表上的排序给我堆栈溢出

时间:2018-10-15 23:28:44

标签: java sorting linked-list mergesort

感谢阅读。我基本上有一个带有通用元素的单链列表(最终传入字符串)...我试图用合并排序对其进行排序,但是由于某种原因我收到了堆栈溢出错误。看来我的递归无休止地进行着,但是我确实有一个条件可以阻止它……这就是我所拥有的,linkedlist类只是具有insertfirst和insertlast的通用链表类。 `公共类应用{

const selectYear = document.querySelector("#selectYear");
selectYear.addEventListener("change", calculateYears);

// Now we get the CURRENT year:
let currentYear = new Date().getFullYear();

// We define it here, globally, so we can just add a value to it and then
// use it within the submit button function.
let yearOfBirth;

function calculateYears(e) {
    // This will get the VALUE of the selected YEAR.
    let birthYear = e.target.options[e.target.selectedIndex].value;

  // We deduct the selected year of birth from current year
  yearOfBirth = currentYear - birthYear;
  console.log(yearOfBirth)

}

// Add a SUBMIT event listener to the FORM
const form = document.querySelector("#form");
form.addEventListener("submit", (e)=>{
    console.log(yearOfBirth)
    // If the result of current year - birth year is greater or equal to 18:
    if(yearOfBirth >= 18) {
       // Take the user to the next page
       alert('you can enter')
       location.replace("https://google.com");
    } else {
      // Don't allow access to the next page, perhaps a modal showing he/she needs
      // to be older or 18 years of age.
      alert("access denied")
    }
    e.preventDefault();
})

}`

再次感谢您。我试图使列表按字母顺序排列,所以基本上是Apple-Bpple-Cpple-Dpple-......等等

第30行出现错误

1 个答案:

答案 0 :(得分:0)

我更新了您的代码并对其进行了一些修改。它可能会解决您的问题。我曾经研究过类似的问题,但它在c ++上仍然可以与Java代码一起使用...让我知道它是否有效并解决了您的问题。

公共静态无效合并(int开始,int中间,int结束,sLinkedList列表) {

sLinkedList tempList = new sLinkedList();
int left = start;    
int right = mid+1; 
int k = start;

while((left<=mid) && (right<=end)) 
{
    if(list.get(left) < (list.get(right)) // compare your if the item on the left is less than the one on the right
    {
        tempList.insertLast(list.get(left));
        left = left+1;
        }
        else {
        tempList.insertLast(list.get(right));

        right++;    

    }
    k++;
}

 for ( int i = left; i <= mid; i++ )
        {
        tempList.insertLast(list.get(i));
            k++;        //moves remaining right list value to temp list
        }

for ( int i = right; i <= end; i++ )
        {
         tempList.insertLast(list.get(i));
            k++;    //moves sorted temp list back to original list
        }

for ( int i = start; i <= end; i++ )

        tempList.insertLast(list.get(i));
        delete tempList;

}