Java链表

链表的理解

在这里插入图片描述
结点分为两部分,结点的数据和结点的引用
结点中的数据指向下一个结点的数据

图中便是 a.next = b;
b.next = null;

Node定义链表

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

MyLinkedList.java

public class MyLinkedList {
	public static Node buildLinkedListHand() {
		//创建一个链表
		Node n1 = new Node(1);
		Node n2 = new Node(2);
		Node n3 = new Node(3);
		Node n4 = new Node(4);
		Node n5 = new Node(5);
		//1 2 3 4 5
		//创建链接
		n1.next = n2;
		n2.next = n3;
		n3.next = n4;
		n4.next = n5;
		
		//返回head头
		return n1;
	}
	 
	 public static void printLinkedList(Node head) {
		 //打印链表
		 Node cur = head;
		 while (cur != null) {
			 System.out.println(cur.val);
			 cur = cur.next;
		 }
	 }
	 
	 public static Node pushFront(Node head, int val) {
		 //头插
		 Node node = new Node(val);//创建一个要插入的结点
		 node.next = head;
		 return node;
	 }
	 
	 public static Node popFront(Node head) {
		 //头删
		 if (head == null) {
			 throw new RuntimeException("空链表");
		 }
		 head = head.next; 
		 return head;
	 }
	 
	 public static Node pushBack(Node head, int val) {
		 //尾插
		 Node node = new Node(val);
		 if (head == null) {
			 throw new RuntimeException("空链表");
		 } else {
			 Node cur = head;
			 while (cur.next != null) {
				 cur = cur.next;
			 }
			 cur.next = node;//跳出时为最后一个结点,将最后一个结点的next改成node
			 return head;
		 }
	 }
	 
	 public static Node popBack(Node head) {
		 //尾删
		 if (head == null) {
			 throw new RuntimeException("空链表");
		 } 
		 if(head.next == null) {
			return null; 
		 } else {
			 Node cur = head;
			 while (cur.next.next != null) {
				 cur = cur.next;
			 }
			 cur.next = null;
			 return head;
		 }
	 }
	 
	 public static void main(String[] args) {
		 Node head = null;
		 head = pushFront(head, 0);
		 head = pushFront(head, 1);
		 head = pushFront(head, 2);
		 head = pushFront(head, 3);
		 head = pushFront(head, 4);
		 head = pushFront(head, 5);
		 head = pushFront(head, 6);
		 printLinkedList(head);
		 
		 head = popBack(head);
		 printLinkedList(head);
		 
		 head = popFront(head);
		 printLinkedList(head);
		
		 head = pushFront(head,0);
		 printLinkedList(head);
		
		 head = pushBack(head, 8);
		 printLinkedList(head);
	 }
}

链表的重点在于理解结点的next
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值