链表insert方法应该怎么改进?

neusimon 2014-05-09 11:49:40
我尝试写了一个有头指针没有头结点的链表,Insert方法各种判断让我我觉得很麻烦,各位大神能不能帮我修改一下?另外我水平很差,如果能都帮我提提其他函数的修改意见也非常欢迎。
代码如下:

public class LinkNode {
public String data;
public LinkNode next;

LinkNode(){
this.data = "a";
this.next = null;
}

LinkNode(String string){
this.data = string;
this.next = null;
}
}



public class LinkList {

public LinkNode head = null;//头指针
private LinkNode currentNode = null;//遍历用节点

LinkList(){}
LinkList(int n){
for(int i = 0; i<n; i++){
add();
}
}

public int getLength(){
if(head == null){
return 0;
}
else{
currentNode = head;
int count = 0;
while(currentNode != null){
currentNode = currentNode.next;
count++;
}
return count;
}
}

//头插法批量添加节点
public void add(){
LinkNode tempNode = new LinkNode();
tempNode.next = head;
head= tempNode;
}

//在第i个节点之后插入新节点
public void insert(int i,String string){
if(getLength() >= i){
LinkNode tempNode = new LinkNode(string);
if(i == 0){ //头指针后插入节点
tempNode.next = head;
head = tempNode;
}
else{
currentNode = head;
if(i == 1){ //第一个节点后插入
tempNode.next = currentNode.next;
currentNode.next = tempNode;
}
else{ //一般位置插入
for(int j =0; j < (i-1); j++){
currentNode = currentNode.next;
}
tempNode.next = currentNode.next;
currentNode.next = tempNode;
}
}
}
else{
System.out.println("要插入的位置不存在");
}
}

//删除第i个节点
public void delete(int i){
if((getLength()>i) && (i>0)){
currentNode = head;
if(i == 1){
head = currentNode.next;
}
else{
for(int j = 1; j<(i-1); j++){
currentNode = currentNode.next;//遍地到要删除节点的前一节点
}
LinkNode tempNode = currentNode.next;
currentNode.next = tempNode.next;
}
}
else{
System.out.println("这个节点不存在");
}
}

public void display(){
currentNode = head;
while(currentNode != null){
System.out.println(currentNode.data.toString());
currentNode = currentNode.next;
}
}

public static void main(String args[]){
LinkList ll = new LinkList(4);
//ll.insert(0,"b");
//ll.insert(1,"b");
//ll.insert(1,"d");
//ll.insert(4,"e");

ll.display();
System.out.println(ll.getLength());
ll.delete(2);
ll.display();
}
}
...全文
825 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
teemai 2014-05-12
  • 打赏
  • 举报
回复
可以参考Java的LinkedList源码
neusimon 2014-05-12
  • 打赏
  • 举报
回复
我真是个2B啊,我记得没有头结点的时候要判断一次是否是第一个节点,只有这两种情况,上面我的insert方法第一个节点后插入和一般位置插入可以直接用一般位置插入就行了,i=1时i-1 = 0啊,j<0所以不会进入for循环,真是的。。
七神之光 2014-05-09
  • 打赏
  • 举报
回复
直接百度一下 答案更多,其实你可以试试 动态申请直接内存来玩玩,挺有意思的
rumlee 2014-05-09
  • 打赏
  • 举报
回复
你的insert方法的参数设置本身就有问题 建议看看数据结构方面的书籍

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧