package code;
class Node
{
Node next;
int data;
public Node(int data)
{
this.data=data;
}
}
class LinkList
{
Node first;
//頭部
public LinkList()
{
this.first=null;
}
public void addNode(Node no)
{
no.next=first;
first=no;//在頭部添加
}
public void delectNode()
{
Node n=first.next;
first=null;
first=n;//在頭部刪除
}
//刪除指定位置
public int Number()
{
int count=1;
//查看有多少元素
Node nd=first;
while(nd.next!=null)
{
nd=nd.next;
count++;
}
return count;
}
public void delectExact(int n)
{
//刪除指定位置
if(n>1)
{
int count=1;
Node de=first;
while(count<n-1)
{
de=de.next;
count++;
}
de.next=de.next.next;
}
else
first=first.next;
}
public void addExact(int n,Node nd)
{
if(n>1)//添加指定位置
{
int count=1;
Node de=first;
while(count<n-1)
{
de=de.next;
count++;
}
nd.next=de.next;
de.next=nd;
}
else
first=first.next;
}
public int findNode(int n)
{
int count=1;//查找一個數對應的位置
Node de=first;
while(de.data!=n)
{
de=de.next;
count++;
if(de==null)
{
return -1;
}
}
return count;
}
public void print()
{
Node no=first;//打印所有
while(no!=null)
{
System.out.println(no.data);
no=no.next;
}
}
}
public class TextNode
{
public static void main(String[] args)
{
LinkList ll=new LinkList();
ll.addNode(new Node(12));
ll.addNode(new Node(15));
ll.addNode(new Node(18));
ll.addNode(new Node(19));
ll.addNode(new Node(20));
/*System.out.println(ll.first.data);
ll.delectNode();
System.out.println(ll.first.data);*/
System.out.println(ll.Number());
ll.delectExact(3);
ll.addExact(3, new Node(100));
System.out.println(ll.Number());
// ll.print();
System.out.println(ll.findNode(112));
}
}
大一菜鳥初學,有誤之處請諒解。