LinkedList的头插法和尾插法

##LinkedList的头插法和尾插法

/*
头插法
public class Node{
public int data;
public Node next=null;//默认指向为空
public Node(){
}
public Node(int value){
	this.data=value;
}
}
public class Test{
public static void main(String[] args){
	Node node=new Node(10);
	node.data=10;
}
}
	
public Node LinkedList_head(){
Node head=null;
String newDate;
while(!(newDate=in.next()).equals("0"))//输入一个数直到0停止
{
	Node newNode=new Node();//新建一个结点
	newNode.data=newDate;
	newNode.next=head;
	head=newNode;
}
return head;
}
//弊端:头结点遍历之后数据会反过来
尾插法
public Node LinkedList_last(){
	Node head=null;//头指针
	Node last=null;//尾指针
	String newDate;
	while(!(newDate=in.next()).equals("0"))
	{
		Node newNode=new Node();//建立头结点
		newNode.data=newDate;
         if(head==null){
            head=newNode;
		 }
        else
		{
       last.next=newNode;	
		}
	last=newNode;
	}
   if(last!=null){
  last.next=null;
 return last;
}	
//遍历之后数据是正确的,相当于增加了一个头结点
//弊端:第一个结点由于没有前驱,在很多时候都要考虑这个结点,最好是在前面再加一个结点,这个结点没有数据指向原来的第一个结点
public Node_creat(){
Node H=null;//头指针
Node R=null;//尾指针
		Node headNode=new Node();//建立头结点
	headNode.next=null;
	H=headNode;
	R=headNode;
	String newDate;
	while(!(newDate=in.next()).equals("0"))
	{
		Node newNode=new Node();
		newNode.data=newDate;
		newNode.next=null;
		R.next=newNode;
		R=newNode;
	}
	R.next=null;
	return H;
}
public class MyLinkedList(){
	public static class Node{//静态内部类
public int data;
public Node next=null;//默认指向为空
public Node(){
	private Node first=null
	private currenr=null;
	public void add(int value){
		//产生一个新的结点
		Node newNode=new Node(value);
		//如果没有任何结点存在(第一个结点)
		if(first=null)
		{
			first=newNode;
			current=newNode;
		}
		//如果不是第一个结点就是后面的结点
		else{
			current.next=newNode;
			current=newNode;
		}
	}
	public void display(){
		Node node=first;
		while(node!=null){
		int value=first.data;
		System.out.println(value);
		node=node.next;
		}
	}
}

}
public Node(int value){
	this.data=value;
}
}*/
public class Test{
public static void main(String[] args){
	Node node=new Node();
	node.data=1;
	for(int i=2;i<=10;i++){
		Node node1=new Node(i,node);//第二个新建的结点将第一个新建的地址给第二个的next
		node=node1;
	}
	printLinkedlist(node);
}
public static void printLinkedlist(Node node){
	while(node!=null){
		System.out.print(node.getData()+" ");
		node=node.getNext();
	}
}
	
}
class Node{
public int data;
public Node next;//默认指向为空
public Node(){
}
public Node(int data,Node next){
	this.data=data;
	this.next=next;
}
public int getData(){
	return data;
}
public Node getNext(){
	return next;
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值