java中链表的一些简单实现方法

import java.util.*;
class Node{
	int val;//data|element
	Node next;//如果next==null表示是最后一个结点
	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 head=null;//head的意思是链表的第一个结点
		//通过第一个结点,就可以找到完整的链表
		//所以,链表的第一个结点往往代表整个链表
		//空的链表,就是一个结点都没有的链表,也就没有第一个结点
		head=pushFront(head,1);
		head=pushFront(head,2);
		head=pushFront(head,3);
		print(head);
		
		
	}
	//head是原来的第一个结点  val是要插入的值   返回是新的第一个节点
	public static Node pushFront(Node head,int val){
		Node node=new Node(val);//结点
		node.next=head;//让原来的head成为node的下一个结点
		//head=node;//更新第一个节点的引用
		return node;
		
	}//头插
	private static void print(Node head) {
		for(Node cur=head;cur!=null;cur=cur.next) {
			System.out.println(cur);
		}
	}//链表的打印
	private Node popFront(Node head) {
		if(head==null) {
			System.err.println("空链表无法作删除");
			return;
		}
		//原来第一个结点,会因为没有引用指向而被回收
		return head.next;
	}//头删
	private Node popBack(Node head) {
		if(head==null) {
			System.err.println("空链表无法删除");
			return;
		}
		if(head.next==null) {
			return null;
		}
		else {
			Node lastSecond=head;
			while(lastSecond.next.next!=null) {
				lastSecond=lastSecond.next;
			}
			lastSecond.next=null;
		}
	}//尾删
	private 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;
		}
	}//尾插
	
	
	

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值