JAVA中数据结构的问题
JAVA中数据结构的问题
我编了一个链表的程序,可使插入那块总是不对,谁能帮帮我
程序:
package linkedlist;
public class LinkedList {
ListNode Node;
ListNode Head;
int count;
public LinkedList() {
Node=new ListNode();
Head=Node;
Node.data=0;
Node.next=null;
count++;
}
public LinkedList(int[] input)
{
Node=new ListNode();
Node.data=input[0];
Head=Node;
count++;
for(int i=1;i<input.length;i++)
{
Node.next=new ListNode();
Node.next.data=input[i];
Node=Node.next;
count++;
}
}
public void Insert(int data,int locate)
{
if(locate<0&&locate>count)
{
System.out.println("error");
}
ListNode temp=Head;
ListNode a;
a=new ListNode();
a.data=data;
for(int i=0;i<locate-1;i++)
{
temp=temp.next;
}
a.next=temp.next;
temp.next=a;
}
public void print()
{
ListNode temp=Head;
for(int i=0;i<count;i++)
{
System.out.println(temp.data);
temp=temp.next;
}
}
public void Delete(int locate)
{
if(locate<0&&locate>count)
{
System.out.println("error");
}
int number=0;
ListNode temp=Head;
ListNode a;
for(int i=0;i<locate-1;i++)
{
temp=temp.next;
}
temp.next=temp.next.next;
}
}
ListNode为链表节点,错误在Insert那里,比如我原来有0,1,2,3,在2前面插入4,应该为0,1,4,2,3
可是现在却是0,1,4,2,不知道为什么,我看了好几遍,没有错呀