某一天的思考題(使用Java實現鏈表)的參考答案

來源:互聯網
上載者:User

題目:使用Java實現鏈表
思路:
鏈表的特點:鏈表的的元素之間通過指標串連起來。通常有一個頭指標指向第一個元素,通過第一個元素可以訪問到其他的元素。
鏈表中資料如何儲存:鏈表中的每個元素應該由表示資料的域和指向其他元素的指標組成。
鏈表的常用操作:建立鏈表、在鏈表中添加元素(在最後添加或者在某個具體的位置添加)、修改鏈表中的元素、刪除鏈表中的元素、查看鏈

表中的元素。
public class  MyList{
      private Element header;
      public MyList(){}
      public MyList(Object o){
          header = new Element();
          header.setValue(o);
          header.setNext(null);
      }
      // 其他動作都很類似,唯寫出添加元素的方法
      public void add(Object o){
           Element temp = header;
           if(temp==null){
                header = new Element();
                header.setValue(o);
                header.setNext(null);
            }else{
                while(temp.getNext()!=null){
                     temp=temp.getNext();
                 }
                 Element new = new Element();
                 new.setValue(o);
                 new.setNext(null);
                 temp.setNext(new);
             }
      }
      // 在某個指定的位置添加元素
      public void add(int index,Object o){
              
      }
      public void setElement(int index,Object o){
                 
      }
}
public class Element{
    private Object value;
    private Element next;
    // setter方法和getter方法
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.