Java写链表的一些插删打印基本操作

class Node{
	int val;
	Node next;
	
	public Node(int val){
		this.val=val;
		this.next=null;
	}
	
	public String toString(){
		return String.format("Node(%d)",val);
		
	}
}

public class MyLinkedList{
	public static void main(String[] args){
		Node node=null;
		Node head=node;
		head = pushFront(head, 0);
		head = pushFront(head, 1);
		head = pushFront(head, 2);
		
		// 打印
		print(head);	// 2 1 0
		
		// 尾插
		head = popFront(head);
		print(head);	// 1 0
		
		head = pushBack(head, 10);
		head = pushBack(head, 20);
		head = pushBack(head, 30);
		print(head);	// 1 0 10 20 30
		head = popBack(head);
		head = popBack(head);
		head = popBack(head);
		head = popBack(head);
		head = popBack(head);
		
		head = popBack(head);	// 报错
		print(head);		// 空
		
		head = pushBack(head, 100);
		print(head);
		
		
	}	
	//插入:
	//1、头插:
	public static Node pushFront(Node head,int val){
		//第一步:将数据封装进结点
		Node node=new Node(val);
		//第二步:将新结点的next指向head
		node.next=head;
		//第三步:更新第一个结点的引用
		return node;
	}
	//2、尾插:
	public static Node pushBack(Node head,int val){
		Node node=new Node(val);
		if(head==null){
			return node;
		}else{
			Node last=head;
			while(last.next!=null){
				last=last.next;
			}
			last.next=node;
			return head;
		}
	}
	//删除
	//1、头删
	public static Node popFront(Node head){
		if(head==null){
			System.err.println("链表为空!");
			return null;
		}else{
			return head.next;
		}
	}
	//2、尾删:
	public static Node popBack(Node head){
		if(head==null){
			System.err.println("链表为空!");
			return null;
		}
		if(head.next==null){
			head=null;
			return head;
		}else{
			Node lastSecond=head;
			while(lastSecond.next.next!=null){
				lastSecond=lastSecond.next;
			}c
			lastSecond.next=null;
			return head;
		}
	}
	public static void print(Node head){
		Node cur=head;
		while(cur!=null){
			System.out.print(cur+"==>");
			cur=cur.next;
		}
		System.out.println("null");
	}
}
发布了78 篇原创文章 · 获赞 4 · 访问量 4179

猜你喜欢

转载自blog.csdn.net/weixin_43580746/article/details/97141333