单链表问题
定义一个单链表,并将数字1-100放入单链表
--------------------编程问答--------------------
import java.util.LinkedList;
import java.util.List;
public class LinkList {
public static void main(String[] args) {
List<Integer> list = new LinkedList<Integer>();
for (int i = 0; i <= 100; i++) {
list.add(i);
}
for (int i : list) {
System.out.println(i);
}
}
}
--------------------编程问答--------------------
--------------------编程问答--------------------
public class Node {
public int data;
public Node next;
public Node()
{
this(0);
}
public Node(int data)
{
this.data=data;
next=null;
}
}
public class MyLink {
public int size;
public Node head;
public MyLink()
{
head=null;
size=0;
}
public void addHead(int data)
{
Node q=head;
head=new Node(data);
head.next=q;
size++;
}
public void add(int data)
{
Node q;
Node p=new Node(data);
if(head==null)
{
head=p;
}
else
{
q=head;
while(q.next!=null)
{
q=q.next;
}
q.next=p;
}
size++;
}
public boolean isEmpty()
{
return head==null;
}
public void display()
{
if(head!=null)
{
Node q=head;
while(q!=null)
{
System.out.print(q.data+"->");
q=q.next;
}
System.out.println();
}
}
public int get(int i) throws Exception
{
Node q=head;
if(head==null)
{
throw new NullPointerException();
}
if(i<0||i>size)
{
throw new Exception("超出范围");
}
int count=0;
while(q!=null)
{
if(count==i)
{
return q.data;
}
count++;
q=q.next;
}
return -1;
}
public boolean delete(int data)
{
Node q=head,p=q.next;
if(head==null)
{
return false;
}
while(q!=null)
{
if(head.data==data)
{
head=q.next;
size--;
return true;
}
if(p.data==data)
{
q.next=p.next;
size--;
return true;
}
q=q.next;
p=p.next;
}
return false;
}
public void add(int i,int data)
{
Node q=head;
int k=0;
while(k<i-1&&q.next!=null)
{
k++;
q=q.next;
}
Node p=new Node(data);
p.next=q.next;
q.next=p;
size++;
}
public static void main(String[] args) throws Exception {
MyLink mylink=new MyLink();
mylink.add(1);
mylink.add(2);
mylink.add(3);
mylink.display();
System.out.println("添加头5");
mylink.addHead(5);
mylink.display();
System.out.println("添加7,9,10");
mylink.add(7);
mylink.add(9);
mylink.add(10);
mylink.display();
System.out.println(mylink.get(3));
System.out.println("删除5");
mylink.delete(5);
mylink.display();
System.out.println("删除3");
mylink.delete(3);
mylink.display();
System.out.println("删除10");
mylink.delete(10);
mylink.display();
System.out.println(mylink.size);
System.out.println("第2个位置添加11");
mylink.add(1,11);
mylink.display();
}
}
--------------------编程问答--------------------
java中有链表吗?用list或者set吧
--------------------编程问答--------------------
谢谢啦!!!
补充:Java , Eclipse