删除链表中的第 k 个元素



我正在尝试编写用于删除链表中第 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是一个Itemk-1解析为int值。 您无法将两者进行比较。您可能打算计算已迭代的节点数。

相关内容

  • 没有找到相关文章

最新更新