Java创建单链表

节点表示:
class Node {
int val;
Node next;
Node(int x) { val = x; }
}

public class MergeTwoSortedLists {
	
	static Node head = null;//链表头的作用
	public static void main(String[] args){
	
        //下面两行是测试,注意当s指向一个节点时,s.next为空,当s没有指向时,s.next不能进行引用
		Node s = new Node(10);
		System.out.println(s.next);
		//也可循环建立
		MergeTwoSortedLists.addNode(10);
		MergeTwoSortedLists.addNode(20);
		MergeTwoSortedLists.addNode(30);
		//打印链表
		MergeTwoSortedLists.printList();
		
    }
    //在尾部插入
    public static void addNode(int d){
	        Node newNode=new Node(d);
	        //处理第一个节点
	        if(head==null){
	            head=newNode;
	            return;
	        }
	        Node tmp=head;
	        //注意插入第二个节点时,这个while不执行
	        while(tmp.next!=null){
	        	System.out.println("111");
	            tmp=tmp.next;
	        }
	        //add Node to end
	        tmp.next=newNode;
	    }
   public static void printList(){
	        Node tmp=head;
	        while(tmp!=null){
	            System.out.print(tmp.val+" ");
	            tmp=tmp.next;
	        }
	        System.out.println();
	    }
}

猜你喜欢

转载自blog.csdn.net/qq_30122883/article/details/82918959
今日推荐