链表
单向链表节点的结构
public class Node {
public int value; // 节点内的值
public Node next; // 指针 指向下一个节点(node)
public NOde(int data){ // 构造方法
value=data;
}
}
双向链表节点结构
public class DoubleNode{
public int value;
public DoubleNode last;
public DoubleNdoe next;
public DoubleNode (int data){
value=data;
}
}
单链表双链表的反转核心代码
public static Node reverseLinkedList(Node head){
Node pre=null;
Node next=null;
while(head!=null){
next= head.next;
head.next=pre;
pre=head;
head=next;
}
return pre;
}
反转双向链表
public static DoubleNode reverseDoubleList(Double head){
Double pre=null;
Double next=null;
while(head!=null){
next =head.next;
head.next=pre; // 两个双向指针 指向的位置 进行互换
head.last =next;
pre=head;
head=next;
}
}
链表中进行数字的删除
Public static Node remobeValue(Node head, int num){
while(head!=null){ // 防止头部第一个数字被删除
if(head.value!=num){
break;
}
head=head.next;
}
// 循环结束 head 来到第一个不需要删除的位置
Node pre =head;
Node cur =head;
// 保证让 cur一直是pre的哨兵指针 用cur判断当前节点的位置是否是要被删除
while(cur!=null){
if(cur.value == num){
pre.next =cur.next;
}else{
pre = cur;
}
cur =cur.next;
}
return head;
}
栈 队列
双线列表 实现
数组 实现
双链表实现栈
public Node <T> head;
public Node <T> tail;
** 从头部进行增加 节点**
public void addFromHead( T value){
Node<T> cur=new Node<T>(value);
if(head==null){ //如果是空连 则这个新加入的节点就是头部 也是尾部
head=cur;
tail =cur;
}else{
cur.next=head;
head.last=cur;
head=cur;
}
}
public static void addFrombottom(T value){
Node<T> = new Node <T>(value);
if(head=null){
head=cur;
tail=cur;
}else{
cur.last=tail;
tail.next=cur;
tail=cur;
}
}
进行弹出
public T popFromHead(){
// 提前判断 链表不为空
if(head==null)
return null;
Node <T> cur=cur; // 建立一个新指针并且指向头节点 装下这个value
if(head==tail){ // 置空链表 表示弹出唯一的节点
head=null;
tail=null;
}else{
cur=head; //将第一个节点赋值给cur
head=head.next; // 更新寻找新的头节点
cur.next=null; // 对其指向下一个位置进行赋空
cur.last=null;
head.last=null; // 对断开新头节点对其的指向
}
return cur.value;
}
双链表实现栈 整体的框架
public static class Mystack<T>{
private DoubleENdsQueue<T> queue;
public MyStack(){
// 此处相当于申请一个节点
queue = new DoubleEndsQueue<T>(); 建立栈
}
public void push(T value){
queue.addFromHead(value); 对栈内进行增加 // 链表实现 即从头部加入
}
public T pop(){
return queue.popFromHead(); 弹出栈 // 链表实现 即从头部弹出 先来先出
}
public boolean isEmpty(){
return queue.isEmpty(); 判断栈是否满了
}
}
双链表中 对栈是 头部进入 头部出
队列是 头部进 尾部出
数组实现 (固定大小 灵活的使用链表)
队列 环状的数组
popindex
putindex
size 通过这个进行判断队列是的容量 入值就++ 否则就–
public static class MyQueue{
private int [] arr;
private int push;
privare int poll;
private int size; // 记录当前队列的大小 该值保证下雨limit
private final int limit; // 表示队列的大小
}
public MyQueue(int limit){
arr= new int[limit];
push =0;
polli=0;
size=0;
this.limit=limit;
}
public void push(int value){
// 先进行判断 在进行入值
if(size==limit){
throw new RuntimeException("栈满了。");
}
size++;
arr[push]=value;
push=nextIndex(push);
}
public int pop(){
if(size==0){
throw new RuntimeException("栈空了");
}
size--;
int ans=arr[polli];
poll=nextIndex(polli);
return ans;
}
public boolean isEmpty(){
return size==0;
}
// 如果现在的下标是i 返回下一个位置
private int nextIndex(int i){
return i<limit-1 ? i+1 : 0 ;
}