package shi.link;import java.util.ArrayList;
public class SeparateLink
{
private static ArrayList<Node> list=new ArrayList<Node>();
public static void main(String args[])
{
Node n1=new Node(1);
Node n2=new Node(2);
Node n3=new Node(3);
Node n4=new Node(4);
Node n5=new Node(5);
Node n6=new Node(6);

LinkNode lb=new LinkNode();
LinkNode la=new LinkNode();
la.addNode(n1);
la.addNode(n2);
la.addNode(n3);
la.addNode(n4);
la.addNode(n5);
la.addNode(n6);

for(int i=0;i<la.getLength();i++)
{

if((la.getNode(i).getData())%2==0)
{
list.add(la.getNode(i));
 // lb.addNode(la.getNode(i));//为什么这里lb直接加节点会出错?
     la.removeNode(la.getNode(i));
  
}
}
for(int j=0;j<la.getLength();j++)
{

System.out.print(la.getNode(j).getData()+" ");

}
System.out.println();
for(int i=0;i<list.size();i++)
{
lb.addNode(list.get(i));
System.out.print(list.get(i).getData()+" ");
}

}

}
class Node
{
private int data;
private Node node;

public Node()
{

}

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

public void setNode(Node node)
{
this.node=node;
}

public int getData()
{
return this.data;
}

public Node getNode()
{
return this.node;
}

}class LinkNode
{
private Node head;
private Node tail;
private static int length;
public LinkNode()
{
head=new Node();
tail=null;
length=0;
}
public void addNode(Node node)
{
if(tail==null)//插入的是第一个节点!
{
head.setNode(node);
node.setNode(tail);
tail=node;
length++; }
else
{
tail.setNode(node);
node.setNode(tail);
tail=node;
length++;
} }
public void removeNode(Node node)
{
if(length==0)
{
System.out.println("链表为空,删除失败!");
System.exit(1);
}
else 
{
Node n=head;
while(n.getNode()!=null)
{
if(node.equals(n.getNode()))
{
n.setNode(node.getNode());
length--;
break;
}
n=n.getNode();

}
}

}

public Node getNode(int index)
{
Node node=head;
for(int i=0;i<=index;i++)
{
node=node.getNode();
}
return node;

}
public int getLength()
{
return this.length;
}
}这是一个简单的链表,链表la中本来有{1,2,3,4,5,6}
题目要求把其中的偶数分离出来放在链表lb中!问题如代码中的注释所说!
结果没办法我只能先把那些节点放在ArrayList里,
而后在放到链表lb里!

解决方案 »

  1.   

    答:shixitong兄弟,你这个class LinkNode类中addNode()和removeNode()方法的代码本身,就有严重的数据结构操作问题啊.怎么能成功呢?兄弟要加强单向链表的数据结构的程序训练呢.
      

  2.   

    你这个链表设计得够怪的
    node自己维护一个向后的node
    node管自己就行了,至于node之间的链接,交给链表维护好了
    重新设计吧,不然你node移来移去的,肯定乱掉