簡體   English   中英

刪除鏈表中的第k個元素

[英]Delete kth element in a linked list

我正在嘗試編寫用於刪除鏈表中第 k 個元素的代碼。 我無法理解這里的錯誤是什么。 如果有人解釋錯誤,我將不勝感激。

            /*
    Write a method delete() that takes an int argument k and deletes the kth element in a linked list if it exists.

    */
    class Deletenode
    {
        private int N;

        private class Node
        {
            String item;
            Node next;
        }

        // Building a Linked List

        Deletenode()
        {
        Node first  = new Node();
        Node second = new Node();
        Node third  = new Node();
        Node fourth = new Node();
        Node fifth  = new Node();
        Node sixth  = new Node();

        first.item  = "to";
        second.item = "be";
        third.item  = "or";
        fourth.item = "not";
        fifth.item  = "to";
        sixth.item  = "be";

        first.next = second;
        second.next = third;
        third.next = fourth;
        fourth.next = fifth;
        fifth.next = sixth;
        sixth.next = null;
    }

        public void delete(int k)
        {
            int i = 1;
            for(Node x = first; x!= null || i== --k; x = x.next,i++)
            {
                if(i == k-1)
                x = x.next.next;
            }

        }

        public void show()
        {
            for(Node x = first; x!= null; x = x.next)
            {
                System.out.print(x.item);
            }
        }

        public static void main(String[] args)
        {
            Deletenode d = new Deletenode();
            d.show();
            d.delete(3);
            d.show();

        }


    }

我得到的錯誤是

            deleteknode.java:44: error: cannot find symbol
            for(Node x = first; x!= null || i== --k; x = x.next,i++)
                         ^
      symbol:   variable first
      location: class Deletenode
    deleteknode.java:54: error: cannot find symbol
            for(Node x = first; x!= null; x = x.next)
                         ^
      symbol:   variable first
      location: class Deletenode
    2 errors

提前致謝

你不能把這樣的代碼直接放在類的主體中。

first.item  = "to";
second.item = "be";
third.item  = "or";
fourth.item = "not";
fifth.item  = "to";
sixth.item  = "be";

first.next = second;
second.next = third;
third.next = fourth;
fourth.next = fifth;
fifth.next = sixth;
sixth.next = null;

將其移動到實例初始值設定項、構造函數或方法並調用它。


此外,您已經為類Item聲明了一個類型參數。 它是無界的,因此您不能僅將String值分配給使用該泛型類型聲明的元素。


還有,這

 if(x == k-1)

沒有意義,因為x是一個Item並且k-1解析為一個int值。 你不能比較兩者。 您可能打算計算您迭代了多少個節點。

暫無
暫無

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

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