java LinkedList的實(shí)例詳解
java LinkedList的實(shí)例詳解
站在Java的角度看,玩隊(duì)列不就是玩對象引用對象嘛!
實(shí)例代碼:
public class LinkedList<E> implements List<E>, Deque<E> {
Node<E> first;
Node<E> last;
int size;
public boolean add(E e) {
final Node<E> l = last;
final Node<E> newNode = new Node<>(l, e, null);
last = newNode;
if (l == null)
first = newNode;
else
l.next = newNode;
size++;
modCount++;
return true;
}
private static class Node<E> {
E item;
Node<E> next;
Node<E> prev;
Node(Node<E> prev, E element, Node<E> next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}
}
單鏈表反轉(zhuǎn):
/**
* 遞歸,在反轉(zhuǎn)當(dāng)前節(jié)點(diǎn)之前先反轉(zhuǎn)后續(xù)節(jié)點(diǎn)
*/
public static Node reverse(Node head) {
if (null == head || null == head.getNextNode()) {
return head;
}
Node reversedHead = reverse(head.getNextNode());
head.getNextNode().setNextNode(head);
head.setNextNode(null);
return reversedHead;
}
/**
* 遍歷,將當(dāng)前節(jié)點(diǎn)的下一個(gè)節(jié)點(diǎn)緩存后更改當(dāng)前節(jié)點(diǎn)指針
*
*/
public static Node reverse2(Node head) {
if (null == head) {
return head;
}
Node pre = head;
Node cur = head.getNextNode();
Node next;
while (null != cur) {
next = cur.getNextNode();
cur.setNextNode(pre);
pre = cur;
cur = next;
}
//將原鏈表的頭節(jié)點(diǎn)的下一個(gè)節(jié)點(diǎn)置為null,再將反轉(zhuǎn)后的頭節(jié)點(diǎn)賦給head
head.setNextNode(null);
head = pre;
return head;
}
對于數(shù)組問題,一般我們要新建數(shù)組,必要時(shí)移動(dòng)下標(biāo)
以上就是java LinkedList 的實(shí)例,如有疑問請留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
MyBatis解決Update動(dòng)態(tài)SQL逗號的問題
這篇文章主要介紹了MyBatis解決Update動(dòng)態(tài)SQL逗號的問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-01-01
Java運(yùn)行時(shí)數(shù)據(jù)區(qū)域(內(nèi)存劃分)的深入講解
聽說Java運(yùn)行時(shí)環(huán)境的內(nèi)存劃分是挺進(jìn)BAT的必經(jīng)之路,這篇文章主要給大家介紹了關(guān)于Java運(yùn)行時(shí)數(shù)據(jù)區(qū)域(內(nèi)存劃分)的相關(guān)資料,需要的朋友可以參考下2021-06-06
Java數(shù)據(jù)結(jié)構(gòu)與算法學(xué)習(xí)之循環(huán)鏈表
循環(huán)鏈表是另一種形式的鏈?zhǔn)酱鎯?chǔ)結(jié)構(gòu)。它的特點(diǎn)是表中最后一個(gè)結(jié)點(diǎn)的指針域指向頭結(jié)點(diǎn),整個(gè)鏈表形成一個(gè)環(huán)。本文將為大家詳細(xì)介紹一下循環(huán)鏈表的特點(diǎn)與使用,需要的可以了解一下2021-12-12
SpringBoot與SpringSecurity整合方法附源碼
這篇文章主要介紹了SpringBoot與SpringSecurity整合,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-01-01
spring aop底層原理及如何實(shí)現(xiàn)
這篇文章主要介紹了spring aop底層原理及如何實(shí)現(xiàn),幫助大家更好的理解和學(xué)習(xí)使用spring aop,感興趣的朋友可以了解下2021-04-04
Springboot 如何指定獲取自己寫的配置properties文件的值
這篇文章主要介紹了Springboot 如何指定獲取自己寫的配置properties文件的值,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-07-07
淺談Java中生產(chǎn)者與消費(fèi)者問題的演變
這篇文章主要介紹了淺談Java中生產(chǎn)者與消費(fèi)者問題的演變,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-10-10

