簡體   English   中英

在Java中將未知數量的節點添加到鏈接列表

[英]Adding unknown number of nodes to a Linked list in java

我有一個項目,我一直在使用鏈表創建不受限制的整數值的地方。 可以通過將String傳遞到構造函數中來實現,然后鏈表的每個節點都包含3位數字。 字符串值將轉換為整數。 我苦苦掙扎的是遍歷字符串並將int正確添加到節點。 另外,數字應以相反的順序存儲,例如,如果數字為123456,則列表將有2個節點。 頭將是654,第二個節點(尾)將是321。

這是我當前的構造函數代碼

public UnboundedInt(String digits){

  head = null;//head of list
  tail = head;//tail of list
  cursor = null;//current node of list
  precursor = null;//node previous to current
  manyNodes = 0;//number of nodes in the list

  String headData;

  for(int i = 0; i < digits.length(); i ++){
     headData = digits.substring(i,i+=3);//creates substring of next 3 
        //digits
     int dataHold = Integer.parseInt(headData);//converts substring to int 
        //value
     IntNode temp = new IntNode(dataHold,null);
     temp.setLink(head);
     head = temp;
     manyNodes++;//increases number of nodes
  }
}

我使用132456789123456789123456789作為測試值,目前在調試中告訴我,我只有7個節點,當前存儲為789 891 456 912 567132。這應該是9個節點。 我確定我缺少一些非常瑣碎的東西,但是任何建議或建議都將不勝感激。 謝謝。

讓我們在這里做一些追蹤

132456789123456789123456789

而使用i+=3substring方法將用於第一個循環,因為

headData = digits.substring(0,3)

這意味着結果將是這樣

loopNo     resultOfSubString    deletedDigit
1                 132                -
2                 567                4
3                 912                8
4                 456                3
5                 891                7
6                 345                2
7                 789                6
           the printed nodes

您應該在每個循環結束時將i的值減1。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM