1.链表的原理
元素:真实存于线性表中的内容,是核心内容。
节点:为了组织链表而引入的一个结构,除了保存我们的元素之外,还会保存指向下一个节点的引用。
class Node{
int val;// 保存我们的元素
Node next; // 保存指向下一个结点的引用;其中尾节点的 next == null
2.代码实现
2.1 链表节点定义
public class ListNode {
public int val;
public ListNode next;
public ListNode(int val){
this.val = val;
this.next = null;
}
public ListNode (int val ,ListNode next){
this.val = val;
this.next = next;
}
@Override
public String toString() {
return "ListNode{" + val +"}";
}
}
2.2链表的头插
public static ListNode pushHead(ListNode head,int val){//头插
ListNode node = new ListNode(val);
node.next = head;
return node;
}
2.3链表的遍历
public static void printtLinkList(ListNode head){
for(ListNode cur = head; cur!=null;cur= cur.next ){
System.out.println(cur.val);
}
}
2.4链表的头删
public static ListNode popHead(ListNode head){//头删
if(head == null){
throw new RuntimeException("链表为空");
}
head = head.next;
return head;
}
2.5链表的尾插
public static ListNode pushBack(ListNode head,int val){
ListNode node = new ListNode(val);
if(head !=null){//判断是否为空链表
ListNode last = head;
while(last.next!=null){
last = last.next;
}
last.next = node;
return head;
}else{
return node;
}
}
2.6链表的尾删
public static ListNode popBack(ListNode head){//尾删
if(head ==null){
throw new RuntimeException("链表为空");
} if(head.next!=null){//判断链表是否只有一个元素
ListNode last = head;
while(last.next.next != null){
last = last.next ;
}
last.next = null;
return head;
}else{
return null;
}
}