微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

无法反转单链表实现的队列中的前 k 个元素

如何解决无法反转单链表实现的队列中的前 k 个元素

这是一个程序,其中前 k 个元素必须在队列中反转,其余元素无效。我试图反转链表并认为它可能会起作用,但它正在删除队列中除第一个元素之外的所有元素。我觉得是有问题在逆向还是应该做不同的处理。谁能帮我这个。 请查看下面的反向功能

我试过调试,但不允许使用递归。 代码如下:

 public void print()
        {
            if(isempty())
            {
                return;
            }
            listnode current=front;
            while(current != null)
            {
                System.out.print(current.data+"--->");
                current=current.next;
            }
            System.out.println("null");
        }
        public void reverse(int pos)
        {
           int c=1;
           listnode curr=front;
           listnode prev=null;
           listnode next2=null;
           while(curr != null && c!=pos)
           {
               next2=curr.next;
               curr.next=prev;
               prev=curr;
               curr=next2;
               c++;
           }
        }
        public static void main(String[] args)
        {
            Scanner sc=new Scanner(system.in);
           lab8_2 queue=new lab8_2();
           int n=sc.nextInt();
           int pos=sc.nextInt();
           for(int i=1;i<=n;i++)
           {
               int x=sc.nextInt();
               queue.enqueue(x);
           }     
           queue.print();
           queue.reverse(pos);
           queue.print();
        }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。