链表中插入链表

zero.yang 2009-07-08 09:55:13
问题:在里面的注释里

public class Node {

private int data;
private Node next;

public Node(int data) {
this.data = data;
this.next = null;
}

public void setData(int data) {
this.data = data;
}

public int getData() {
return data;
}

public Node getNext() {
return next;
}

public void setNext(Node next) {
this.next = next;
}

}


public class LinkList {

Node head;

public LinkList() {
head = null;
}

}



//实现将输入的数组转化成单链表,并将其插入到给出的单链表的指定位置
public static LinkList linkInsert_L(LinkList l, int idx, int[] arrs){
int count=0;
Node tail=null;
//将数组转换成链表
LinkList head = new LinkList();
for(int i=0;i<arrs.length;i++){
Node d = new Node(arrs[i]);
if(head.head == null){
head.head = d;
}else{
tail.setNext(d);
}
tail = d;
count++;
}
//统计l的节点数
Node t = l.head;
int lc=0;
while(t != null){
lc++;
t=t.getNext();
}

if(idx<1){
tail.setNext(l.head);
l.head=head.head;
}else if(idx>=lc){
Node ltail=l.head;
for(int i=1;i<lc;i++){
ltail=ltail.getNext();
}
ltail.setNext(head.head);
}else{
//问题:代码就加在这里,当链表插在中间任意位置是怎么写啊
}


return l;
}
...全文
148 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
bigbug9002 2009-07-08
  • 打赏
  • 举报
回复
错了,应该是:
n.setNext(p.getNext());
p.setNext(n);
bigbug9002 2009-07-08
  • 打赏
  • 举报
回复
思路:要找到插入位置的前一个结点p ,如果插入的结点是,n;

n.setNext()=p.getNext();
p.setNext()=n;
就可以了
zero.yang 2009-07-08
  • 打赏
  • 举报
回复
请大家,给出详细的的答案

62,614

社区成员

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

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