java链表数据插入在第N个位置.为什么函数insertN()不起作用?

编程入门 行业动态 更新时间:2024-10-28 20:22:44
本文介绍了java链表数据插入在第N个位置.为什么函数insertN()不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

class Link{ public String val; public Link nextlink; public Link(String val) { this.val = val; } public void linkNext(Link l){ this.nextlink=l; } public void printlink() { System.out.print(" "+val); } } class linkList{ Link first; public static int count=0; public linkList(){ first=null; } boolean isEmpty(){ return first==null; } public void insertfirst(String str){ Link next=new Link(str); count++; next.nextlink=first; first=next; } public void insertN(int pos,String str){ if(pos<count){ Link temp=first; count++; for(int i=0;i<pos-1;i++) temp=temp.nextlink; Link next=new Link(str); next=temp.nextlink; temp=next; } } public void printList(){ Link currentLink=first; System.out.println("data is:"); while(currentLink!=null){ currentLink.printlink(); currentLink=currentLink.nextlink; } System.out.println(" "); } } public class LinkedList2 { public static void main(String[] args) { linkList li=new linkList(); li.insertfirst("neeraj"); li.insertfirst("rohit"); li.insertfirst("lalit"); li.insertfirst("meenu"); li.printList(); li.insertfirst("newly"); li.insertN(9, "newlaay"); li.printList(); System.out.println(li.count); } }

推荐答案

1. 为什么要public static int count=0;? 这意味着每个实例只有一个count,请删除static! 2. 将成员变量的访问权限更改为private. 3. 将方法linknext 更改为setNextLink,这是Java中的一个很好的约定. 4. insertFirst必须使用方法setNextLink,因为成员varianble无法访问: 1. Why public static int count=0;? That means there is a single count for every instance, remove the static! 2. Change the access for the member variables to private. 3. Change method linknext to setNextLink, this is a convention in Java that works well. 4. insertFirst must use the method setNextLink, as the member varianble cannot be accessed: public void insertFirst(String str) { Link next = new Link(str); count++; next.setNextLink(first); first=next; }

5. insertN将无法按计划工作.允许Link类为您完成工作:

5. insertN will not work as planned. Allow the Link class to do the work for you :

class Link // stuff Link getLink (int position) { if (position <= 0 || this.nextlink == null) { return this.nextLink; } else { return this.nextlink.getLink(position - 1); } } }

然后在位置后添加:

Then to add after a position:

public void insertAfter(int pos,String str){ Link previous = this.first.getLink(pos); if (previous != null) { Link next = previous.getNextLink(); Link insert = new Link(str); previous.setNextLink(insert); insert.setNextLink(next); } }

简单且减少错误的代码.

Simple and less code to go wrong.

更多推荐

java链表数据插入在第N个位置.为什么函数insertN()不起作用?

本文发布于:2023-11-29 19:09:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647353.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   不起作用   链表   位置   数据

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!