拖了N天的一篇博客...本来学完链表就应该写了,但是链表题比较多,难度也不小,于是就小拖了一下,今天把栈和队列的题也弄完了终于...来还债了。
3.5上迪希雅!一整个期待住了,须弥最喜欢的角色之一!
链表
线性结构存储,无需担心扩容问题,头插方便,如果是双向链表的话,对尾的操作也很方便。带头的用起来会省很多事,但是偏偏很多题就是考你不带头的,因为不带头结点的话要考虑得更多。
还可以有循环结构,即头尾相接,这样组合更多了,还可以有双向循环,实现起来当然复杂,但是对于使用者而言,会方便很多,正所谓,前人栽树,后人乘凉嘛。
关于链表的具体知识我也不赘述了,网上或者站内有太多太多详解了,我在这里只是做一个简单回顾。题目的话我有空会另外写博客,接下来我把我写的两个来链表贴一下吧,一个单向无头链表,一个双向无头链表,链表涉及到引用的修改操作,实现起来不算难但是细节非常多,所以还是要非常仔细的学习。
无头单向不循环链表
public class MyLinkList {
public int size;
public ListNode head;
//头插法
public void addFirst(int val){
ListNode newhead = new ListNode(val);
newhead.next = this.head;
this.head = newhead;
this.size++;
}
// 尾插法
public void addLast(int val){
ListNode cur = this.head;
if(cur == null) {
cur = new ListNode(val);
return;
}
while(cur.next != null){
cur = cur.next;
}
cur.next = new ListNode(val);
this.size++;
}
//任意位置插入,下标从0开始
public boolean addIndex(int index,int val) {
if (index > this.size){
addLast(val);
}else if(index == 0){
addFirst(val);
}else {
int count = 1;
ListNode cur = this.head;
while (count < index) {
cur = cur.next;
}
ListNode newnode = new ListNode(val);
newnode.next = newnode.next;
cur.next = newnode;
}
size++;
return true;
}
//查找关键字key是否在单链表当中
public boolean contains(int key){
ListNode cur = this.head;
while(cur != null){
if(cur.getVal() == key){
return true;
}
}
return false;
}
//删除第一次出现key的节点
public boolean remove(int key){
ListNode cur = this.head;
ListNode prev = cur;
while(cur != null){
if(cur.getVal() == key){
break;
}
prev = cur;
cur = cur.next;
}
if(cur == null)
return false;
if(cur == this.head){
this.head = cur.next;
cur.next = null;
this.size--;
return true;
}
if(cur.next == null){
prev.next = null;
this.size--;
return true;
}
prev.next = cur.next;
cur.next = null;
this.size--;
return true;
}
//删除所有值为key的节点
public void removeAllKey(int key){
while(remove(key));
}
//得到单链表的长度
public int size(){
return this.size;
}
//打印单链表
public void display(){
ListNode cur = this.head;
while(cur != null){
System.out.print(cur.getVal());
if(cur.next != null)
System.out.print("->");
cur = cur.next;
}
System.out.println();
}
//清除单链表
public void clear(){
ListNode cur = this.head;
this.head = null;
while(cur != null){
ListNode next = cur.next;
cur.next = null;
cur = next;
}
this.size = 0;
}
}<

本文回顾了链表、栈和队列的基本概念和实现方式,包括无头单向、双向不循环链表的实现,以及数组栈、链表栈、链表队列和数组链表的探讨。特别指出链表操作中的细节和优化,以及栈的先进后出特性。文章以LeetCode题目为例,帮助深化对这些数据结构的理解。
最低0.47元/天 解锁文章
533





